Multithreading: the IAsyncResult interface

Published Mon, Jun 8 2009 8:54

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.

Filed under: ,

Comments

# LA.NET [EN] said on Wednesday, June 10, 2009 6:09 AM

In this post we’re going to take a look at how we can use polling to see if an asynchronous task has

# ASPInsiders said on Wednesday, June 10, 2009 6:34 AM

In this post we’re going to take a look at how we can use polling to see if an asynchronous task has

Leave a Comment

(required) 
(required) 
(optional)
(required)