Thursday, March 02, 2006

Beware of asynchronous methods calls that can complete synchronously. Part 1

In .NET every method can be executed asynchronously, it means that it will be executed in the separate thread, typically ThreadPool thread. Here is sample code…

class Program
{
public delegate void LongMethodDelegate();

static void Main(string[] args)
{
Console.WriteLine("Main thread: {0}",
Thread.CurrentThread.ManagedThreadId);

LongMethodDelegate @delegate =
new LongMethodDelegate(LongRunningMethod);

IAsyncResult ar = @delegate.BeginInvoke(
new AsyncCallback(OnComplete), null);
ar = @delegate.BeginInvoke(new AsyncCallback(OnComplete), null);
//@delegate.EndInvoke(ar);

Console.ReadLine();
}

static void LongRunningMethod()
{
Thread.Sleep(10000); //long running task
Console.WriteLine("--------- LongRunningMethod");
Console.WriteLine("Executing on thread: {0}",
Thread.CurrentThread.ManagedThreadId);
}

static public void OnComplete(IAsyncResult ar)
{
Thread thread = Thread.CurrentThread;

Console.WriteLine("--------- OnComplete");
Console.WriteLine("Completed on thread: {0}\n" +
"Synchronously: {1}\n" +
"ThreadPool thread: {2}\n" +
"IsBackground thread: {3}",
thread.ManagedThreadId,
ar.CompletedSynchronously.ToString(),
thread.IsThreadPoolThread.ToString(),
thread.IsBackground.ToString());
}
}

Everything is pretty simple here, LongRunningMethod() is executed on the separate thread, OnComplete is called when LongRunningMethod()is completed. The thread that completes the work is called WorkerThread.

While using this approach – method that is being called asynchornously will be executed on the separate thread… However, if you noticed IAsyncResult has CompletedSynchronously property. What for? It is a good question, and I hope soon it will be answered :8-)

No comments:

Post a Comment