Pattern
Uses two methods: BeginOperationName
and EndOperationName
BeginOperationName
- Contains the same parameters as the synchronous version of the method and two additional parameters:
- An
AsyncCallback
delegate that references a method that is called when the async op completes - A user-defined object
- An
- Returns an
IAsyncResult
IAsyncResult
- Members:
AsyncState
AsyncWaitHandle
CompletedSynchronously
IsCompleted
EndOperationName
- Contains the same parameters as the synchronous counterpart and an
IAsyncResult
parameter - The
IAsyncResult
passed in must be the same one that originated from theBeginOperationName
method- Passing other
IAsyncResult
objects is undefined. - Calling
EndOperationName
multiple times with the sameIAsyncResult
object is undefined.
- Passing other
Sequencing
- Call BeginOperationName
- If there is additional work to perform (blocking is not needed), either:
- Poll for operation completion status by checking
IsCompleted
periodically, then callEndOperationName
when op is complete - Use an AsyncCallback
- Poll for operation completion status by checking
- If blocking is needed (no additional work to be performed), either:
- Call
EndOperationName
from the app’s main thread. This blocks execution until the op is complete. - Use the
AsyncWaitHandle
to block until one or more ops completes.
- Call
Performing additional work (no blocking needed)
Polling for operation completion
IAsyncResult result = BeginOperationName(…, null, null);
while (result.IsCompleted != true)
{
// Do additional work
}
var returnValue = EndOperationName(result);