Synchronizing threads
The async/await pattern has made life easier for us developers. If you have a long-running task (and remember: anything that uses devices outside the CPU is long-running), you can call that method asynchronously. Then you can sit back and wait for it to finish without blocking the execution of your app in other places. The TPL takes care of the thread management.
However, sometimes you may want to have a bit more control. You might have a situation where you must wait for a method to finish before you can continue. Imagine that you have your main thread and call the A()
method. That method is long-running, so you make it async (rename it to something ending with ‘async’) and change the return type to Task
or Task<>
. Now you can wait for it. However, another thread might have to wait until your Aasync()
method is finished. How do you do that?
Welcome to the wonderful world of thread synchronization.