Home > Uncategorized > Asynchronous Programming in C#

Asynchronous Programming in C#

I’m reading Whitepaper: Asynchrony in .NET from the main MSDN Visual Studio Asynchronous Programming

Very exciting stuff!

Here’s the sentence that sums up the significant changes:

“So instead of taking a callback as a parameter, an asynchronous method now returns a representation of the ongoing work.”

It’s also not often that you see such excitement in a MSDN Whitepaper such as this:

“At first glance the await keyword looks like it blocks the thread until the task is complete and the data is available, but it doesn’t. Instead it signs up the rest of the method as a callback on the task, and immediately returns. When the awaited task eventually completes, it will invoke that callback and thus resume the execution of the method right where it left off!”

Here’s an easy way to spawn a background thread from the thread pool:

Task<double> task = Task.Run(() => LongRunningComputation(x, y, z));

See note in Whitepaper, if using the CTP installed on .NET 4, you would use TaskEx instead.

Here’s the link to Task Parallelism (Task Parallel Library)

There are a couple of other conventions around the Task-based Asynchronous Pattern (TAP), including how to handle cancellation and progress. These are further described in the Task-based Asynchronous Pattern document included in the Async CTP.

The section “Event handlers and void returning async methods” illustrates how to convert a UI component’s event handler into a void async method. This allows the UI to continue processing (disregarding any Task as there is none in a void return), and allows the event handler itself the freedom to perform significant processing. Excellent, this has been a significant issue when developing WP7 MVVM applications.

Not only methods but also lambda expressions can be async. Among other things this allows event handlers to be anonymous. Another useful application of asynchronous lambdas is for running asynchronous work on a background thread. Task.Run has overloads that expect delegates of type Func and Func<Task> so that you can easily express this.

Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s

%d bloggers like this: