事件是Inversion of Control (IoC) 模式的一种特殊情况。传统的控制流,调用者调用被调用者的方法(就像你建议的那样)。使用 IoC(以及事件),我们围绕应用程序控件进行更改,而不是告诉被调用者要做什么,而是告诉被调用者在我们感兴趣的事情发生时通知我们。
考虑Timer 的情况。我想每 5 秒收到一次通知(比如说)。我不想一直poll the timer(“是时候了吗?是时候了吗?是时候了吗?”)。相反,我想反转我的应用程序的流控制。我想告诉计时器:“时间到了,请通过调用这个方法告诉我。”这样,控制是“反转”的,被调用者正在调用调用者的方法!
考虑下面的代码...
using System;
using System.Timers;
namespace TestTimer
{
class Program
{
static void Main(string[] args)
{
// create my timer.
var t = new System.Timers.Timer(1000);
// register for notification
// tell the timer, "when it's time, call TimerGoesOff method"
t.Elapsed += new ElapsedEventHandler( TimerGoesOff );
// start the timer
t.Start();
// wait
Console.ReadLine();
}
// this gets called when the timer goes off
public static void TimerGoesOff(object source, ElapsedEventArgs e)
{
Console.WriteLine("The Time is " + e.SignalTime);
}
}
}
我没有在 Timer 上调用一个方法来询问它何时会再次关闭(如您所建议的那样),而是告诉它,“当您关闭时,调用 TimerGoesOff”方法。现在,我可以做一些工作,而不仅仅是等待计时器响起。考虑这段代码...
using System;
using System.Threading;
using System.Timers;
namespace TestTimer
{
class Program
{
static void Main(string[] args)
{
// create my timer.
var t = new System.Timers.Timer(1000);
// register for notification
t.Elapsed += new ElapsedEventHandler( TimerGoesOff );
// start the timer
t.Start();
// do some work while timer is going
new Thread(() => DoWork()).Start();
Console.ReadLine();
}
// this gets called when the timer goes off
public static void TimerGoesOff(object source, ElapsedEventArgs e)
{
Console.WriteLine("The Time is " + e.SignalTime);
}
public static void DoWork()
{
for (int i = 0; i < 5; i++)
{
Console.WriteLine( "Working ..." );
Thread.Sleep( 1000 );
}
}
}
}
现在,我得到的输出类似于 ...
Working ...
The Time is 8/25/2009 1:05:59 PM
Working ...
Working ...
The Time is 8/25/2009 1:06:00 PM
Working ...
The Time is 8/25/2009 1:06:01 PM
Working ...
The Time is 8/25/2009 1:06:02 PM
The Time is 8/25/2009 1:06:03 PM
我使用Timer.Elapsed Event 更改了我的应用程序的控制流。我可以在“等待”计时器事件发生脉冲的同时下班工作。 IoC 和事件使这成为可能。
这在用户界面中尤其明显(呵呵)。我不想一直问“用户做了什么了吗?用户做了什么了吗?” (这就是过去的方式)。相反,我告诉 Controls,例如,“当用户点击你时,让我知道”。这样一来,我就可以开始做其他很棒的事情,同时仍能响应用户。