Asynchronous Programming in .NET – Part 1

Oct 31st, 2010 | By | Category: Framework & Libraries

.NET Framework allows us to execute some methods asynchronously without blocking the calling program.These asynchronous methods are executed on different threads thus allowing the calling program to do it’s own job after the other method has been invoked.In this kind of asynchronous programming scenarios,in general we expect the following features to be implemented.

  1. Ability to perform certain tasks( execute methods) in a different thread without blocking the calling thread.
  2. Ability to execute another method on completion of the asynchronous method (callback).
  3. Ability to check the status of the task (busy,completed etc.) being performed using a different thread.
  4. Ability to get information about the progress of the task.
  5. Ability to cancel the task.
  6. Ability to handle the exceptions generated by the asynchronous operation.

To implement the above mentioned features in a structured manner .NET Framework provides two asynchronous programming patterns:

  • Asynchronous Programming Model(APM)
  • Event based Asynchronous Pattern

In this post we will discuss primarily about the Asynchronous Programming Model.This pattern is in place since .NET 1.1 and most prevalently used asynchronous programming pattern in the .NET world so far.Let us consider the following method of System.IO.FileStream class

public override int Read(byte[] array, int offset, int count)

This is the synchronous version of the method and blocks the calling thread until read is complete.The asynchronous version of the method (,actually two methods)  which supports the APM pattern is shown below:

public override IAsyncResult BeginRead(byte[] array,int offset,int numBytes,AsyncCallback userCallback,Object stateObject)
public override int EndRead(IAsyncResult asyncResult)

So here we can see that synchronous version of the method is broken into two methods.As per APM each method will be broken into two

    • One with name BeginXXX which actually starts the execution of the method in different thread
      • In addition to the normal method parameters it accepts two additional parameters
        • An Sytem.AsyncCallback object which wraps the callback method to be invoked after the asynchronous method execution completes.
        • A System.Object instance which stores the state information unique to that asynchronous call
      • The method always returns a System.IAsyncResult type.
    • Another with EndXXX which actually waits for the pending operation to be complete
      • The method accepts a parameter of System.IAsyncResult type

To understand this better we need to take a detailed look into System.IAsyncResult and System.AsyncCallback.

System.IAsyncResult interface defines the status of an asynchronous operation with the following properties:

  • AsyncState – This is a System.Object instance representing state of the asynchronous operation
  • AsyncWaitHandle – This is a System.Threading.WaitHandle instance used for waiting on the asynchronous call to complete
  • CompletedSynchronously – Indicates if the method call is completed synchronously
  • IsCompleted – Indicates if the asynchronous call is completed or not.This is a non blocking call and immediately returns with a true/false value.

System.AsyncCallback is a delegate with following definition and used to refer to the method to be invoked after the asynchronous operation completes:

public delegate void AsyncCallback(IAsyncResult ar)

This pattern provides following different mechanisms of implementation:

  • Direct call to EndXXX method
            FileStream fs = new FileStream(@"C:\test.txt",FileMode.Open);
            byte[] b = new byte[1000];
            IAsyncResult r = fs.BeginRead(b,0,b.Length,null,fs);
  • Use of callback method
static void Main(string[] args)
    FileStream fs = new FileStream(@"C:\test.txt",FileMode.Open);
    byte[] b = new byte[1000];
    AsyncCallback cb = new AsyncCallback(Callback);
    IAsyncResult r = fs.BeginRead(b,0,b.Length,cb,fs);
public static void Callback(IAsyncResult ar)
    FileStream fs = (FileStream)ar.AsyncState;
    int bytesRead = fs.EndRead(ar);
  • Polling for completion
<p> FileStream fs = new FileStream fs = new FileStream(@"C:\test.txt",FileMode.Open);
 byte[] b = new byte[1000];
 IAsyncResult r = fs.BeginRead(b,0,b.Length,null,fs);
 while (true)
     if (r.IsCompleted) break;
 int bytesRead = fs.EndRead(r);
  • Wait using WaitHandle
FileStream fs = new FileStream(@"C:\test.txt",FileMode.Open);
byte[] b = new byte[1000];
IAsyncResult r = fs.BeginRead(b,0,b.Length,null,fs);
int bytesRead = fs.EndRead(r);

This pattern does not support exception handling,cancellation & progress monitoring explicitly.For this we have to explore the Event Based Asynchronous Pattern in the next post.

NOTE: The snippets shown above are for demo purposes and not much useful from practical standpoint.

Kick It on
Tags: , ,
  • Twitted by silverfighter

    [...] This post was Twitted by silverfighter [...]

  • Tweets that mention Asynchronous Programming in .NET – Part 1 – Coding N Design —

    [...] This post was mentioned on Twitter by silverfighter, Kunal Chowdhury, Abhijit Jana, Abhishek Sur, Vaibhav Sharma and others. Vaibhav Sharma said: RT @sankarsan Asynchronous Programming in .NET – Part 1 #dotNET #CSharp #Async #Programming #Code [...]

  • Asynchronous Programming in .NET – Part 2 – Coding N Design

    [...] the last post we have discussed about the Asynchronous Programming Model(APM) and it’s different [...]