Random Noise

cat /dev/random >> /dev/dsp

Archive for September 2007

Asynchronous Delegates in .NET 2.0

leave a comment »

One of the good features of .NET 2.0 is Asynchronous Delegates. Use these when you want to maintain the application responsive and reliable. Especially when the application wants to complete an IO call, database call, web service call or number crunching (CPU intensive) that can take up fairly long time. For example refreshing of the UI is handled by a single main thread. Which means all the events such as mouse click, mouse movement, keyboard events and even displaying text to the console are handled by this single thread. In this case we were told that we should use threads, i.e. spawn a worker thread and return quickly. But in .NET it is efficient to re-use threads, i.e. borrow them from .NET ThreadPool and not instantiate them. Jeffrey Richter goes on to describe in detail why so in this interview. To simply summarize Jeffrey I can say that spawning a new thread is a costly affair. One of the ways to re-use/borrow threads is to use Asynchronous Delegates. Asynchronous pattern basically involves fire and forget. Once the result is available .NET will call back a method that you must specify during the initial call.

The .NET runtime generates BeginInvoke and EndInvoke methods for each delegate defined. BeginInvoke is a non blocking method and returns right away.Lets take an example of a method that takes long time

public int MySlowTask(int someInput)
{
//simulate slow task
Thread.Sleep(20);
Console.WriteLine(“Processed input : {0}”,someInput);
return someInput+1;
}

In order to call a method asynchronously we must define a delegate with same method singnature as that method.

delegate int SlowTaskDelegate(int someInput);
SlowTaskDelegate slowTaskDelegate = MySlowTask;

Then we call the BeginInvoke method to call the long task asynchronously.

slowTaskDelegate.BeginInvoke(10, // Input parameter to MySlowTask()
EndInvokeMySlowTask, // Callback Method
slowTaskDelegate); // AsyncState

We must also write EndInvokeMySlowTask method (a callback method) that the runtime calls after completing the task.Its signature is fixed defined as
void MethodName(IAsyncResult result):

public void EndInvokeMySlowTask(IAsyncResult result)
{
SlowTaskDelegate myDelegate = result.AsyncState as SlowTaskDelegate;
// obtain the result
int resultVal = myDelegate.EndInvoke(result);
Console.WriteLine(“Returned output : {0}”,resultVal);
}

Advertisements

Written by Vivek Unune

September 9, 2007 at 2:30 am

Posted in .NET

Tagged with , , ,