Powered by Blogger.

Task in Dot Net


The task helps us write code without worrying about all the things required to execute an async program like creating a delegate making sure heavy/time taking computations are run in the background. Dot Net already has multiple approaches for handling async programming like Threads, Async Programming model (delegate invocation), QueueUserWorkItem so where does Task fit in.

Tasks are the next level of abstraction on top of the threading interface, it provides a more robust exception handling mechanism, helps us write clean code (threads and async programming has been notoriously complicated to write and maintain) which in turn helps in maintainability.

There are 2 methods to create Tasks:

Task t = new Task(/*code to be executed*/);
t.Start();

Here we create a task, have all the code that needs to be executed inside a Task, and then call the start method. Another way is,

Task t = Task.Factory.StartNew((/*code to be executed*/)

This one line does exactly the same thing as the above 2 lines but is more efficient.

What happens when we start a Task, application on executing “t.start()” forks and creates 2 code streams executing concurrently which helps us to make the application more responsive. One very important thing to keep in mind when working with Task is about updating a UI. We can not update/modify UI elements in any way from a Worker thread or from a task running in a Background. We need to make sure that the code which is responsible for updating result on UI  is executed on a UI thread and this can be achieved by using the keyword “TaskScheduler.FromCurrentSynchronizationContext()” as shown in full example below.

Above on button click, we create a Task which does some processing like making a Web Service call, expensive object manipulation, anything that can take more than a blink of an eye. Once that task finishes updating the UI to show the result we attach the task “t” with another task using the keyword “ContinueWith” which makes sure that once the main task is completed only then this task gets executed. Also, notice the second parameter for “ContinueWith” which takes a “TaskSchedule”, this tells the application that the code inside the “ContinueWith” should be executed on the current context i.e. on the current UI thread.


And that’s it, just create a Task, make sure there is no processing of UI inside that task, then once the task completes executing the UI code on the current context and voila we have async programming and our application is fully responsive.

Please note that the above code in no way is improving the performance of the application because we are still doing things one at a time, we are just making sure that the application does not wait on UI thread for a long-running process.

No comments