Hitesh
Hitesh

Reputation: 1228

Difference between join and await in thread

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

Upvotes: 9

Views: 9396

Answers (1)

Micah Zoltu
Micah Zoltu

Reputation: 7432

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.

Upvotes: 4

Related Questions