If you are writing multi threaded application with .Net , there are various options to choose from. There is Thread,Background worker, delegate etc.
.Net framework 4.5 has introduced another approach towards parallel programming "async and await". With async n await, code follows a logical structure which looks similar to synchronous code and provides benefits of asynchronous programming.
Here Act_Async is an asynchronous method which makes a call to GetStreamAsync and after that performs some operations (which are some print operation for ex.). Once those operation are complete and it requires the output of GetStreamAsync , it await on the return object (which is stream in this case). Once await is called, control is returned to the calling code (which is main method).
In Main method, once the control comes back it performs some operation (which are again some print operation for ex.) and the thread is never blocked. when it needs the output from Act_Async method, and if Act_Async method has not come back yet, it waits for it to come back. Once the results are back, it proceed with the result for further processing .
Below is similar method written using Thread class.
Some of the key differences-
- You need to make use of a shared variable which thread updates since ThreadStart delegate can not point to a method which returns a value (difficult to use with functional programming) while async method can return an object.
- The flow of the code is not as smooth as with async n await. code may look similar but code with async n await is much more easy to understand and follows a sequential structure.
- The flexibility with using Thread is that You can manage it ( Do you really want to !!!) like setting up background/foreground , priority etc .
There may be some cases where you need certain notification on progress of parallel tasks (some of these are provided in background worker class) those are not available here but you can use async n await in almost any case where you are using any other threading approach for parallel processing.
For more details , visit MSDN.
Comments
Post a Comment