My Advices for Parallel and Async programming.

The biggest reason I’m writing this post, is when I started to write async and await pattern,there were few questions about this pattern, and this post going to explore them.

What is the difference between Parallel and Async?

To answer this question, we need to ask the following Question:

Is it CPU bound or I/O bound work?

CPU-bound work means: we want to iterate over big in memory collection of objects, by using the TPL like PLINQ, Parallel.For, Parallel.Foreach, or we want to execute very complex calculation process.

When we use the Task Parallel Library the compiler feel out how many threads needed to make the best progress to our job.

Good to know that use of TPL not always run in parallel, and increase throughput on a machine that’s under load.

For example:

If we have list of person object and we want to sort the list as parallel, use the following code:

var orderedPersons = Persons.AsParallel().OrderBy(x => x.Age);

I/O bound work means: we write code that’s bound by the time of network or I/O requests, and then we need to use Asynchronous code.

By using the async and await pattern the compiler generates the appropriate code, to do the asynchronous job behind the scene.

Async Behind the Scene:

In the .NET 4.5, when any method marked with the async and await, the compiler implement the method into two code blocks:

Stub method – contains the initial set up information for the asynchronous method, and starts the state machine generated by the c# compiler.

State machine – maintains the state of the asynchronous method, where it start and where he need to be after the asynchronous process finish.

For example:

If we have a WPF application that responds to button click event, and the click event needs to download data from the server asynchronously:

async void Button_Click(object sender, RoutedEventArgs e){

await LoadDataAsync();

}

async Task LoadDataAsync(){

await DownloadAsync();

}

When the compiler encounter’s the await keyword he return the work flow back to the caller, so if the await call come from the UI thread, that means the program stay responsive to the UI interaction. When the answer comes from the network, then the Task marked as completed and the compiler jump to the point he awaited.

Async void is a fire and forget mechanism:

  1. When we write Async void method, the method return void to the caller so the caller is unable to know when the async void work has finished.
  2. Exceptions and Async void methods, when exception thrown from async void method, the caller is unable to catch the exception, and it throws strait to the UI thread or the main thread, and that’s can crash the entire application.

Cancelling Async Operation:

If we want to implement cancellable async operation, we can use the overload Task method that accepts a System.Threading.CancellationToken.

CancellationTokenSource cts = new CancellationTokenSource();

private Task<IEnumerable<Person>> LoadDataAsync()

{

Task<IEnumerable<Person>> res = new Task<IEnumerable<Person>>(obj =>

{

return GetData();

}, cts);

res.Start();

return res;

}

If the token has cancellation requested and the asynchronous operation is able to respect that request, the returned task will end in the TaskStatus.Canceled state; there will be no available Result and no Exception.

Summary:

Then if we decide to parallelize our code, we need to keep in mind the following details:

  • Async pattern is useful for IO and network bound work.
  • TPL pattern is usefule for data bound work.
  • Async void is fire and forget mechanism.
  • Async doesn’t solve everything.
  • TPL not always runs in parallel.

Want to learn more?

http://blogs.msdn.com/b/lucian/archive/2013/06/28/talk-the-complete-async-three-talks-from-teched-europe-2013.aspx

Advertisements

About Idan Reuven

Idan is Microsoft Certified Proffesional Developer (MCPD) Idan Working As Senior Software developer. and specialize in professional application development with WPF, WCF, Entity Framework, XAML, HTML 5, Java Script , jQuery, MVC, MVVM, C#, C++, SQL Server Technologies.
This entry was posted in .NET 4.5, C# 5. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s