原來invoke一個event handler會執行所有加入的event,
執行的順序,大致是先加入的event, 先執行。
但這順序,不一定是固定的。
要查看目前有多少event加入到event handler,
可使用InternetConnectionAvailableEvent.GetInvocationList().Length;
Sample Code (參 C# 6.0 in a Nutshell):
public delegate void ProgressReporter(int percentComplete);
public class Util
{
public static void HardWork(ProgressReporter p)
{
for (int i = 0; i < 10; i++)
{
p(i * 10); // Invoke delegate
System.Threading.Thread.Sleep(100); // Simulate hard work
}
}
}
class Test
{
static void Main()
{
ProgressReporter p = WriteProgressToConsole;
p += WriteProgressToFile;
//Util.HardWork(p);
p.Invoke(1);
Console.WriteLine(p.GetInvocationList().Length);
Console.ReadKey();
}
static void WriteProgressToConsole(int percentComplete)
=> Console.WriteLine(percentComplete);
static void WriteProgressToFile(int percentComplete)
=> Console.WriteLine(percentComplete*5);
//=> System.IO.File.WriteAllText("progress.txt",
// percentComplete.ToString());
}
沒有留言:
張貼留言