Friday, 26 October 2018

Task-based Asynchronous Pattern (TAP)

Parallelizing with TAP:
However, the biggest benefit of using TAP or async/await in general is the possibility of the creation of different workflows within the same method. What this means is that we can combine multiple Tasks in several ways, and by doing so, we are changing the flow of our method and our application. For example, consider that you have this situation in your application:
This would mean that tasks would be executed sequentially. The second task would run only after the first one is finished, and the third task would run only after the second one is finished.
async Task RunWorkflow()
{
       var stopwatch = Stopwatch.StartNew();

       // Task 1 takes 2 seconds to be done.
       await Task.Delay(2000)
              .ContinueWith(task => Completed("Task 1", stopwatch.Elapsed));

       // Task 2 takes 3 seconds to be done.
       await Task.Delay(3000)
              .ContinueWith(task => Completed("Task 2", stopwatch.Elapsed));

       // Task 3 takes 1 second to be done.
       await Task.Delay(1000)
              .ContinueWith(task => Completed("Task 3", stopwatch.Elapsed));

       // Print the final result.
       Completed("Workflow: ", stopwatch.Elapsed);
       stopwatch.Stop();
}

void Completed(string name, TimeSpan time)
{
       Console.WriteLine($"{name} : {time}");
}
So, in here, we assumed that Task 1 would take two seconds to finish the job, Task 2 would take three seconds and finally Task 3 would take one second to be done. After that, we used the ContinueWith method, which is basically creating another task which will execute asynchronously once the Task is done. Also, keep in mind that I used .NET Core 2.0 for this application. It is important to use .NET Core or .NET Framework 4.7 in order for this example to work. The result looks like something like this:
There it is, we achieved sequential workflow. Now, this is something we don’t usually want to happen in our application. More often we want our application to run multiple parallel tasks and continue with execution only when they are all done, such as seen on example:
In order to make this work, we can exploit the WhenAll method of the Task class, that we had the chance to encounter in the previous blog post. That would look like something like this:
async Task RunWorkflow()
{
       var stopwatch = Stopwatch.StartNew();

       // Task 1 takes 2 seconds to be done.
       var task1 = Task.Delay(2000)
              .ContinueWith(task => Completed("Task 1", stopwatch.Elapsed));

       // Task 2 takes 3 seconds to be done.
       var task2 = Task.Delay(3000)
              .ContinueWith(task => Completed("Task 2", stopwatch.Elapsed));

       // Task 3 takes 1 second to be done.
       var task3 = Task.Delay(1000)
              .ContinueWith(task => Completed("Task 3", stopwatch.Elapsed));

       await Task.WhenAll(task1, task2, task3);

       // Print the final result.
       Completed("Workflow: ", stopwatch.Elapsed);
       stopwatch.Stop();
}

void Completed(string name, TimeSpan time)
{
       Console.WriteLine($"{name} : {time}");
}
Here, instead of awaiting every Task, we used a different tactic. Firstly, we created an instance of every task and then used the WhenAll method of the Task class. This method creates a task that will finish only when all of the defined tasks have finished. Here is how it looks like when we run this code:
Now, this is much better, as you can see Tasks run in parallel and the whole workflow lasted as long as operation Task 2. Yet sometimes we want to finish the workflow as soon as the first Task is done. Imagine if you are pulling data from multiple servers and you want to continue processing as soon as the first one responds. We can do that using the Task class as well, or to be more specific, the WhenAny method of the Task class. The workflow would look like something like this:
In our case Task 3 will first finish the execution so we want to continue processing as soon as that task is done. The code won’t differ too much from the previous example:
async Task RunWorkflow()
{
       var stopwatch = Stopwatch.StartNew();

       // Task 1 takes 2 seconds to be done.
       var task1 = Task.Delay(2000)
              .ContinueWith(task => Completed("Task 1", stopwatch.Elapsed));

       // Task 2 takes 3 seconds to be done.
       var task2 = Task.Delay(3000)
              .ContinueWith(task => Completed("Task 2", stopwatch.Elapsed));

       // Task 3 takes 1 second to be done.
       var task3 = Task.Delay(1000)
              .ContinueWith(task => Completed("Task 3", stopwatch.Elapsed));

       await Task.WhenAny(task1, task2, task3);

       // Print the final result.
       Completed("Workflow: ", stopwatch.Elapsed);
       stopwatch.Stop();
}

void Completed(string name, TimeSpan time)
{
       Console.WriteLine($"{name} : {time}");
}
In a nutshell, we are just calling the WhenAny method instead of the WhenAll method, which essentially creates a task that will finish when any of the supplied tasks have completed. Running this code will print this on the output:
We can see that the output looks a tad weird. Still, it makes much sense. What happened is that Task 3 has finished, which caused our WhenAll task to complete. This, on the other hand, caused our Workflow to be completed and with that our two remaining tasks as well.
You might ask yourself “Well, is there a way to create a workflow that will not cut out those two last tasks?” and that would be a good question. What we would like to see is something like this:
This scenario is possible in the cases when we want to do a small amount of processing after each of the different tasks has been finished. This can be achieved again by using the WhenAll method of the Task class and a simple loop:
async Task RunWorkflow()
{
       var stopwatch = Stopwatch.StartNew();

       // Task 1 takes 2 seconds to be done.
       var task1 = Task.Delay(2000)
              .ContinueWith(task => Completed("Task 1", stopwatch.Elapsed));

       // Task 2 takes 3 seconds to be done.
       var task2 = Task.Delay(3000)
              .ContinueWith(task => Completed("Task 2", stopwatch.Elapsed));

       // Task 3 takes 1 second to be done.
       var task3 = Task.Delay(1000)
              .ContinueWith(task => Completed("Task 3", stopwatch.Elapsed));

       var tasks = new List<Task>() { task1, task2, task3 };

       while (tasks.Count > 0)
       {
              var finishedTask = await Task.WhenAny(tasks);
              tasks.Remove(finishedTask);
              Console.WriteLine($"Additional processing after finished Task! {tasks.Count} more tasks remaining!");
       }

       // Print the final result.
       Completed("Workflow: ", stopwatch.Elapsed);
       stopwatch.Stop();
}

void Completed(string name, TimeSpan time)
{
       Console.WriteLine($"{name} : {time}");
}
So when we run this code we will get this output:







7 comments:

  1. Interesting information and attractive.This blog is really rocking... Yes, the post is very interesting and I really like it.I never seen articles like this. I meant it's so knowledgeable, informative, and good looking site. I appreciate your hard work. Good job.
    Kindly visit us @
    Sathya Online Shopping
    Buy AC Online | AC Online Shopping | AC Price | Buy Air Conditioner Online
    Inverter Split AC | Best Inverter AC | Split AC Price | Buy Split AC Online
    Smart LED TV | Smart TV Price | LED TV Online | Buy LED TV Online
    Laptop Online | Laptop Price | Buy Laptop Online | Best Laptop
    Buy HD LED TV
    Buy Ultra HD TV Online
    Buy Mobile Online | Buy Smartphone Online in India

    ReplyDelete
  2. The article is very interesting and very understood to be read, may be useful for the people. I wanted to thank you for this great read!! I definitely enjoyed every little bit of it. I have to bookmarked to check out new stuff on your post. Thanks for sharing the information keep updating, looking forward for more posts..
    Kindly visit us @
    Madurai Travels
    Best Travels in Madurai
    Cabs in Madurai
    Tours and Travels in Madurai

    ReplyDelete
  3. Excellent Blog. I really want to admire the quality of this post. I like the way of your presentation of ideas, views and valuable content. No doubt you are doing great work. I’ll be waiting for your next post. Thanks .Keep it up!
    Kindly visit us @ Christmas Gift Boxes | Wallet Box | Perfume Box Manufacturer | Candle Packaging Boxes | Luxury Leather Box | Luxury Clothes Box | Luxury Cosmetics Box | Shoe Box Manufacturer | Luxury Watch Box

    ReplyDelete