摘要:一个简单的程序,用了 IAsyncResult 去实现异步操作。 MyWork() 内部通过delegate 调用了非托管的com 组件,但是,当这个程序在[STAThread] 状态下运行时,delegate 死活没有执行,程序进入死循环。
public void Test1()
{
MyWork work = new MyWork();
IAsyncResult ar = work.BeginWork(); //begin the async action
while (!ar.IsCompleted) //<--- this loop will run forever in an WinForm app.
{
//show progress
Thread.Sleep(50);
}
if (ar.IsCompleted)
{
work.EndWork(); // get the result.
}
}
搞了半天,高手指点把Thread.Sleep() 换成 Thread.CurrentThread.Join(50) 就可以了!
虽然MSDN 对两个方法的解释是一样的:
Thread.Join
Blocks the calling thread until a thread terminates or the specified time elapses.
Thread.SleepBlocks the current thread for the specified number of milliseconds.
但是它们有细微而重要的区别,根据这个BLOG :
Thread.Sleep is a little unusual. We can take control of threads that......[
阅读全文]