C# -- 使用委托 delegate 执行异步操作
委托是一种安全地封装方法的类型,它与 C 和 C++ 中的函数指针类似。 与 C 中的函数指针不同,委托是面向对象的、类型安全的和保险的。
委托的类型由委托的名称定义。
1. 使用委托异步执行方法
class Program
{
public delegate void myWorking(string s); static void Main(string[] args)
{
Console.WriteLine("主线程开始....线程ID:{0}", Thread.CurrentThread.ManagedThreadId);
myWorking myWork1 = new myWorking(w1 => Working(w1));
myWorking myWork2 = new myWorking(w2 => Working(w2));
myWorking myWork3 = new myWorking(w3 => Working(w3));
myWorking myWork4 = new myWorking(w4 => Working(w4));
myWorking myWork5 = new myWorking(w5 => Working(w5)); //回调函数
AsyncCallback callback=new AsyncCallback(s=>Console.WriteLine("执行完成,线程ID:{0}",Thread.CurrentThread.ManagedThreadId)); //BeginInvoke异步执行,会新启动其他线程去执行代码
myWork1.BeginInvoke("唱歌", callback,null);
myWork2.BeginInvoke("写代码", callback, null);
myWork3.BeginInvoke("查资料", callback, null);
myWork4.BeginInvoke("交作业", callback, null);
myWork5.BeginInvoke("检查", callback, null); Console.WriteLine("主线程结束....线程ID:{0}", Thread.CurrentThread.ManagedThreadId);
Console.ReadKey();
} private static void Working(string strWork)
{
Console.WriteLine(strWork+".....线程ID:{0}",Thread.CurrentThread.ManagedThreadId);
Thread.Sleep();
}
}
2. 执行结果: