Multithreading: the IAsyncResult interface

In the last post, we’ve started looking at the APM model used by the .NET framework. Today we’re going to talk about the role played by the IAsyncResult interface. Currently, the IAsyncResult interface has the following members:

public interface IAsyncResult {
    object AsyncState { get; }
    WaitHandle AsyncWaitHandle { get; }
    bool CompletedSynchronously { get; }
    bool IsCompleted { get; }
}

The AsyncState property lets you access the state parameter passed to the BeginXXX method. The AsyncWaitHandle property is a WaitHandle which you can use to wait on (it’s only one of the options you have for waiting). Most implementations tend to use a ManualResetEvent object which gets signaled when the operation completes.

The CompletedSynchronously property lets you know if the operation completed in synchronous or asynchronous fashion. You might be curious on why you need this property. After all, won’t the APM always complete asynchronously? The answer to this is a little more complicated than it may appear at first sight…Most of the time, operations will complete asynchronously and this property will return false. In fact, most frameworks that implement the APM rely in the thread pool and will always return false.

However, the APM model is also used by I/O and, in those cases, there’s the chance of the I/O operation completes in a synchronous fashion. When this happens, it means that the thread that called the BeginXXX method, will also handle the EndXXX method. if you were to start another asynchronous I/O call from within the callback, you could end up using all the stack and getting a stack overflow exception.

Finally,there’s the IsCompleted property,which ends up returning true when the work is done.

As you can see, there’s not much into consuming an IAsyncResult interface. The problematic part is implementing it. We’ll return to that in the future, but before doing that, let’s see what options we have for waiting for the completion of an asynchronous operation when we use this mode.

Keep tuned for more on multithreading.

Advertisements

~ by Luis Abreu on June 8, 2009.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: