两段小代码
private Action<int> sleep = second =>
{
Console.WriteLine("enter Action");
Thread.Sleep(second * 1000);
PrintThread();
Console.WriteLine("leave Action");
};
public void AsynT()
{
PrintThread();
Console.WriteLine("begin");
var result = sleep.BeginInvoke(2, null, null);
Console.WriteLine("continue");
sleep.EndInvoke(result);
Console.WriteLine("end");
}
public void AsynOption()
{
PrintThread();
var waiter = new ManualResetEvent(false);
Console.WriteLine("begin");
sleep.BeginInvoke(2, callback =>
{
//callback.AsyncWaitHandle.WaitOne();
Console.WriteLine("end");
sleep.EndInvoke(callback);
waiter.Set();
}, null);
Console.WriteLine("continue");
waiter.WaitOne();
//Console.Read();
}
在执行第二个方法的时候,我们可以会发现,如果去掉 ManualResetEvent 以后, callback代码不执行了。这是为什么呢?
经过仔细研究后,发现,
sleep.BeginInvoke(2, callback =>相当于
sleep.BeginInvoke(2,new AsynCallback(…..)…..
使用回调方法。
从MSDN查到原因如下:
The callback is made on a ThreadPool thread. ThreadPool threads
are background threads, which do not keep the application running
if the main thread ends.