Storage Informer
Storage Informer

Use lambda expressions in C# to simplify the parallelized code II

by on May.19, 2009, under Storage

Use lambda expressions in C# to simplify the parallelized code II

In my previous post :Use lambda expressions in C# to simplify the parallelized code; I began talking about the advantages of using lambda expressions in parallelized code.

I used a very simple example. Now, I・m going to use a more complex example to convince you that lambda expressions and parallelized code are good friends. In this post, I・m going to forget about the Task Parallel Library Beta 1 because I・m going to use a C# example for Silverlight.

You have a Silverlight application showing a simple Button through XAML code, btnStartGame. If you want to change its properties from a non-UI thread, you have to queue commands in the UI thread. You cannot change controls・ properties from other threads.

If you have to create a new thread, start it and invoke a delegate to update the UI inside it, the code could be as complex as the following lines:

// The event handler that starts the thread
private void btnStartGame_Click(object sender, RoutedEventArgs e)
{
Thread thread = new Thread(new ThreadStart(InvokeThread));
thread.Start();
}

// The code that will run in a new thread
void InvokeThread()
{
btnStartGame.Dispatcher.BeginInvoke(UpdateContent);
}

// The code that will run in the UI thread to update the text shown in the Button
void UpdateContent()
{
btnStartGame.Content = "New title.";
}

The code is indeed complex. It contains too many lines and three methods.

Now, let・s take a look at the same code, but using lambda expressions:

private void btnStartGame_Click(object sender, RoutedEventArgs e)
{
new Thread(() =>
{
btnStartGame.Dispatcher.BeginInvoke(() => btnStartGame.Content = " New title.");
}).Start();
}

The code is indeed simpler. Just a few lines and they fit in the event handler. You can replace the creation of many methods using lambda expressions. Hence, lambda expressions in C# are good friends for task-based programming.

Just a note, you have to add using System.Threading; in order to make the code run in a Silverlight 2 or Silverlight 3 Beta 1 solution.

URL: http://feedproxy.google.com/~r/IntelBlogs/~3/MRq9DdK8G9w/

:, , , , ,

Leave a Reply

Powered by WP Hashcash

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...