Join : Blocks the calling thread until a thread terminates
await : suspend the execution of the method until the awaited task completes
What are the other difference between join and await.
Can any one help me when we can use join and when we can use await?
Thanks, HItesh
The difference is that launch returns a Job and does not carry any resulting value, while async returns a Deferred -- a light-weight non-blocking future that represents a promise to provide a result later.
wait() method is primarily used for the inter-thread communication. On the other hand join() is used for adding sequencing between multiple threads, one thread starts execution after first thread execution finished.
A good way to think about this is to imagine that asynchronous methods have “pause” and “play” buttons. When the executing thread reaches an await expression, it hits the “pause” button and the method execution is suspended.
Join is a synchronization method that blocks the calling thread (that is, the thread that calls the method) until the thread whose Join method is called has completed. Use this method to ensure that a thread has been terminated. The caller will block indefinitely if the thread does not terminate.
Join and await are quite different. In the most simple and broad terms, Join is the old way of doing threading, await is the new way. If ever in doubt, go with await and save yourself a lot of headache.
To go into more detail, if you manually create a thread using var thread = new Thread(MyRunMethod); thread.Start()
(or something similar) and you want to wait for that method to finish then you will need to call thread.Join()
on it later if you want to wait for it to finish before continuing on with your program. In this scenario, if you want results from the function you will need to make sure you deal with thread synchronization yourself and put locks in all of the right places so you don't end up reading partial data later on.
With the async await model, you can let the Framework deal with optimizing thread usage and all you have to do is step through another level of abstraction when utilizing results. In this situation, there is no need to deal with thread synchronization or locking, all of that is handled for you by the Framework.
public async Task<String> GetGoogle()
{
var result = await new WebClient().DownoadString("http://www.google.com");
return result;
}
public void Main()
{
Console.WriteLine(GetGoogle().Result);
}
Another important difference is that Thread.Join will block the thread you call that in (consuming some resources) while it waits. By using await ...
you are releasing the current thread to do other things wile you wait for the thing to finish.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With