Thread. Sleep vs. thread. currentthread. Join

Source: Internet
Author: User

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.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.