C# 异步回调的不解 ?

来源:百度知道 编辑:UC知道 时间:2024/09/25 07:04:53
高级编程中的一个示例,主线程输出".",委托线程执行一个规定时长的方法takeMethod,执行完后执行takecompleted:
class Program
{
public delegate void takedelegate(int ms);
public static void takeMethod(int ms)
{
Console.WriteLine("开始执行 ");
Thread.Sleep(ms);
Console.WriteLine("执行完毕 ");
}
static void Main(string[] args)
{
takedelegate dl = takeMethod;
dl.BeginInvoke(3000, takecompleted, dl);
for (int i = 0; i < 100; i++)
{
Console.Write(".");
Thread.Sleep(50);
}
}
static void takecompleted(IAsyncResult ar)
{
takedelegate dl2 = ar.AsyncState as takedelegate;
}
}
请问,IAsyncResult ar是怎么捕获到 dl的?是因为dl.BeginInvoke;的最后一个参数强制转换为IAsyncResult了?没有找到dl.Be

把你的程序改成这样你就清楚了:

class Program
{
public delegate void takedelegate(int ms);
public static void takeMethod(int ms)
{
Thread.Sleep(ms);
}
static void Main(string[] args)
{
takedelegate dl = takeMethod;
IAsyncResult ar = dl.BeginInvoke(3000, takecompleted, new object[] { "a","b","c",1,2,3});
//dl.EndInvoke(ar);
Console.WriteLine("开始执行");
for (int i = 0; i < 100; i++)
{
Console.Write(".");
Thread.Sleep(50);
if (ar.IsCompleted)
{
Console.WriteLine("执行完毕 ");
break;
}
}
Console.Read();
}
static void t