1. A simple program uses iasyncresult to implement asynchronous operations. Mywork () internally calls the unmanaged COM component through Delegate. However, when the program runs in the [stathread] State, the delegate is not executed, and the program enters an endless loop.
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.
}
}
After a long time, you can change thread. Sleep () to thread. currentthread. Join (50!
Although msdn has the same interpretation of the two methods:
Thread. Join
Blocks The Calling thread until a thread terminates or the specified time elapses.
Thread. Sleep
Blocks the current thread for the specified number of milliseconds.
However, they have minor and important differences. According to this blog:
Thread. Sleep is a little unusual. We can take control of threads that are inside this service. But, following the tradition of sleep on the underlying Windows operating system, we perform no pumping.
If you need to sleep on an sta thread, but you want to perform the standard COM and sendmessage pumping, consider thread. currentthread. Join (timeout) as a replacement.