Task

April 27, 2020

Threads are the most low-level constructs when it comes to multithreading. However work with threads could be very challenging. Let’s say I need a sudden value from worker thread return back to the main thread, the only way is using Join and another variable to retrieve value.. It works, but it can get complicated. So tasks come to our rescue. Task is a higher level abstraction and they’re capable of returning value. Tasks are very handy because they are compositional in nature. In fact you can use continuation and chain any amount of tasks together. Tasks are capable of using thread pool and one of the best feature about Tasks is, They’re very handy for I/O bound operations.

So as you see we could wait, and get the result if we define task as generic with return type.

Now we would want to wait task and get the value, well, if we do not really wait for tasks, there is another way to do this, which is we can actually use the task.result property. and the task.result property has one advantage to it that will wait till the entire task is completed. It’ll actually block the execution to line number 15, wait for the task to execute and then provide the result, which is pretty good but at the same time, since it’s blocking, we need to understand when to use it and how to use it. One thing too keep in mind is that if there is any unhandled exception that get re-thrown whenever you query the tasks result property, it will actually get wrapped in an aggregate exception. Any time we are going for the result property or we are doing task will wait, if the task still executing, the current thread will actually wait.

Recently with async , await keyboard, a lot of people start using .result property which is actually the same concept and they make the same exact mistake. For the most part if you use .result property you don’t have to use .wait keyboard.

task.wait or task.result both of them block the execution and will wait, by using any of them you can get the aggregate exception, so be careful of using any of them inside try catch.

Continuation

A continuation is an asynchronous task that is invoked by another task, which is known as antecedent, when antecedent finishes.
We could pass data from antecedent to continuation and not only that we could pass exception and let the continuation task handle the exception. There is also options to make it conditional if continuation will be invoked. There is control to cancel continuation not only before it starts but even while it’s running. We can also invoke multiple continuation from the same antecedent. At the same time you can invoke continuation when any of antecedents complete or you can do that when all antecedents complete too.

Leave a Reply:

Your email address will not be published. Required fields are marked *