Async / Await and SynchronicationContext (C# .Net)

Following innocuous looking async / await code will cause deadlock.

private void button1_Click(object sender, EventArgs e)
{
  Task<string> task1 = LongRunningProcess();

  textBox1.Text = task1.Result;
}

public async Task<string> LongRunningProcess()
{
  string txt = await Task.Run(() =>
    {
      System.Threading.Thread.Sleep(5000);
      return "results";
    }
  );

  return txt;
}

To understand why, lets go into what await does in the above case.

1 Execution starts when the button is clicked and button1_Click event is fired on the UI thread.
2 The method, named LongRunningProcess, is invoked.
3 The lamda expression passed to Task.Run() executes in a separate thread (lets call it thread_B)
4 Now await keyword is encountered, rather than completing the rest of the method, control returns back to button1_Click event to continue execution after the call to long running method.
5 Calling task1.Result makes the current thread wait on thread_B to complete and provide the results. So UI thread is now waiting for thread_B to complete.
6 As thread_B completes the task, it has to run the remaining part of long running method. Run time ensures that this code executes on the right context. That is, if the initial part of long running method was executed on the UI thread, then remaining part will also be executed in the same thread context.
7 Therefore, thread_B now attempts to run the remaining part of long running method on UI thread, while UI thread is waiting for thread_B to finish.
8 As UI thread and thread_B are waiting for each other, this creates the deadlock.
How to avoid deadlock?

In this case, deadlock can be avoided by anyone of the following ways:

1- Use await keyword while calling long running method. This makes the button click event asynchronous also.

private async void button1_Click(object sender, EventArgs e)
{
  textBox1.Text = await LongRunningProcess();
}

2- Call ConfigureAwait(false), this will inform the run time that the remaining part of long running method doesn’t need to execute on the UI thread, it can continue running on the thread pool.

public async Task<string> LongRunningProcess()
{
  string txt = await Task.Run(() =>
    {
      System.Threading.Thread.Sleep(5000);
      return "results";
    }
  ).ConfigureAwait(false); //avoids the deadlock

  return txt;
}
Why thread contexts are synchronized?

Consider the UI Controls (Windows Forms or WPF), they are not thread safe. Therefore, any update to the UI controls must be done only from the UI thread. To take care of this, any remaining code after await keyword in an asynchronous method will also execute on the thread context which initiated the method call.

Similarly, in an ASP.Net application, running the code on same thread context is important because the Culture, Principal and other information of the request are stored in the thread.

How thread contexts are synchronized?

To manage all this tricky context synchronization, we have SynchronizationContext class in .Net. There are framework specific implementations (derived classes) for Windows Forms, WPF/Silverlight and ASP.Net which handle the SynchronizationContext in their own ways for the framework to function properly.

The Windows Forms implementation uses Control.Invoke method to accomplish this (more details here). For ASP.NET, execution takes place on a different thread but the context is captured and passed on to the new thread.

There is an excellent article on MSDN regarding the SynchronizationContext which I recommend for details.

 

Creating and Consuming Async methods (C# .Net)

The code we want to run asynchronously could either be CPU-bound or IO-bound. CPU-bound code keeps the CPU busy, requiring intensive processing, calculations etc. On the other hand, IO-bound code frees up the CPU while waiting for an IO operation to complete, for instance, get some data from a web service. Both kinds of asynchronous methods are illustrated below.

 

 Creating Asynchronous method

 

CPU-bound Async method
public async Task<string> OurMethodAsync()
{
  string x = await Task.Run(() =>
    {
      // performs CPU intensive work
      return LongRunningTask();
    });

  return x;
}

Above method doesn’t do anything special. Rather than performing the work itself, it creates a thread and delegates the work to it. It will not make the task run faster, in fact, it may take more time due to multi-threading overhead. One reason to do things this way is to free the calling thread and not keep it busy for long time. This is required in case of User Interface threads, for instance.

 

IO-Bound Async method

For IO operation such as working with file system, requests to web servers etc., .Net framework already provides us with methods which run asynchronously. These methods uses lower levels OS calls to provide asynchronous behavior for blocking IO operations.

Below is our asynchronous method which uses .Net Framework’s WebClient.DownloadStringTaskAsync method.

public async Task<string> GetWebPage(string url)
{
  var webClient = new WebClient();
  string txt = await webClient.DownloadStringTaskAsync(url);

  return txt;
}

 

 Consuming asynchronous method

 

Consuming asynchronous method with await
private async void button1_Click(object sender, EventArgs e)
{
  textBox1.Text = await GetWebPage("http://www.yahoo.com");
}

 

This button click event consumes the IO-bound async method defined above. If GetWebPage method is taking a long time, the control will return back to the caller method. Once results of GetWebPage are available, execution will start again with the instruction after await keyword. This will ensure that the event does not block the UI thread.

Calling asynchronous methods concurrently

We can also use asynchronous method to run tasks in parallel.

private async void button1_Click(object sender, EventArgs e)
{
  Task<string> task1 = GetWebPage("http://www.yahoo.com");
  Task<string> task2 = GetWebPage("http://www.google.com");

  await Task.WhenAll(task1, task2);

  textBox1.Text = task1.Result;
  textBox2.Text = task2.Result;
}

 

Notice we are not using await keyword now when invoking GetWebPage method. This causes the return type to change also, we are expecting Task rather than string object.

The flow control is also very different. If GetWebPage is blocking, the control doesn’t return to the caller method, rather execution continues to the next statement in the event.

We have await in the third line which will relinquish control to the caller method if task1 or task2 are not completed yet. When the result of the two tasks are available the last two lines of code are executed on the UI thread.

Reached “Design – All Star” in design .toolbox

"All Star - Design" @ .toolbox

.toolbox is a really fun environment to learn basic design concepts as well as the fundamentals of creating Silverlight applications using Expression Studio. Today, I finished both the tracks (i.e. principles and scenarios) and achieved all 15 badges. The high quality tutorials and evaluations, and a very nice theme make it really enjoyable. Check it out at http://www.microsoft.com/design/toolbox/

Microsoft Visual Studio LightSwitch

Visual Studio LightSwitch is a new tool from Microsoft for developing business applications. Currently available development technologies from Microsoft (like VS C#) are general purpose and can be used to develop a wide variety of applications. LightSwitch, on the other hand, is focused on simplifying development of business applications by handling the basic plumbing itself.

I downloaded the currently available Beta1 version of LightSwitch and started playing with it. It took about 5 minutes to get following application ready.


Employee Information Sample App

The above sample application supports addition, updation and deletion of employee records along with employee qualifications and skills. It is an impressive output considering the effort that was put in.

I performed the following steps to develop the sample app.

  1. Click on ‘create table’ in App Designer, name the table as Employee and define its attributes.
  2. Do the same as step 1, for Qualification and Skill.
  3. Create the relationship two relationships using designer i.e. employee-qualification and employee-skills.
  4. Click on  ‘new screen’ in App Designer and specify the table and desired layout.
  5. Hurrah! Application is ready.

 

LightSwitch Application Designer:

Following is the LightSwitch application designer for tables. Additional settings are available for each attribute from the properties window.

LightSwitch Table Designer
LightSwitch Table Designer

 

Below is the screen shot of application designer for screens. I didn’t make any changes here except changing the display names for qualification and skill tabs.

LightSwitch Screen Designer

 

LightSwitch also has a query designer. Queries can also be used as a basis of screen design apart from tables. Following screen shot shows the query designer.

LightSwitch Query Designer

 

Key Features:

  • We can extend the functionality of LightSwitch application by writing code in C#.Net or VB.Net. LightSwitch allows the developers to easily hook their business logic in application events. We can even write a custom control or fully custom screen.
     
    I believe this is the single most important feature of LightSwitch, this is where most of the LightSwitch precursors struggled.
Screen Shot shows partial list of methods which can be implemented for a table. Screen designer has a similar 'Write Code' functionality with method like loaded, closed etc.

 

  • Another important feature is the ability of LightSwitch to connect to various data sources, its not tied up to a particular back-end technology. It support Sql Server, Azure (Cloud), SharePoint, Entity Framework as data sources.
  • The application generated by LightSwitch is a Silverlight application. It runs in out-of-browser mode if application type is desktop. So multiple platforms are supported.
  • Support Master details screen (e.g. invoice and invoice lines)
  • Support searching, sorting and paging of records without writing any code.
  • Support user authentication and role based security using ASP.Net Membership Provider.
  • Handle image as one of the basic attributes of an object.

 

LightSwitch Links:

Save and Load RichTextBox content in WPF

The content of RichTextBox can be saved to a file (or any other stream) using TextRange class. It supports following four formats:

  1. System.Windows.DataFormats.Text : This saves the plain text in the content of RichTextBox excluding the formatting information and the images.
  2. System.Windows.DataFormats.Rtf : This saves the content in RTF format preserving formating information and images.
  3. System.Windows.DataFormats.Xaml : This saves the content in Xaml format which is the same format used in WPF designer for specifying content for a RichTextBox. It contains formating tags but doesn’t support image.
  4. System.Windows.DataFormats.XamlPackage : This is a binary file format which packages Xaml and any images into one file.

Following table is presenting key information about above formats:

Format Binary/Text Formating Supported Images Supported
Text Text No No
Rtf Binary Yes Yes
Xaml Text Yes No
XamlPackage Binary Yes Yes

The code for saving & loading is pretty simple once who know the relevant class. Following is the code for saving content to file.

TextRange t = new TextRange(richTextBox1.Document.ContentStart,
                                    richTextBox1.Document.ContentEnd);
FileStream file = new FileStream("Sample File.xaml", FileMode.Create);
t.Save(file, System.Windows.DataFormats.XamlPackage);
file.Close();

 

 

Following snippet is for loading the content of RichTextBox from a file.

TextRange t = new TextRange(richTextBox1.Document.ContentStart,
                                richTextBox1.Document.ContentEnd);
FileStream file = new FileStream("Good File.xaml", FileMode.Open);
t.Load(file, System.Windows.DataFormats.XamlPackage);
file.Close();