pattern
Uses two methods: BeginOperationName and EndOperationName
BeginOperationName
- Contains the same parameters as the synchronous version of the method and two additional parameters:
- An
AsyncCallbackdelegate that references a method that is called when the async op completes - A user-defined object
- An
- Returns an
IAsyncResult
IAsyncResult
- Members:
AsyncStateAsyncWaitHandleCompletedSynchronouslyIsCompleted
EndOperationName
- Contains the same parameters as the synchronous counterpart and an
IAsyncResultparameter - The
IAsyncResultpassed in must be the same one that originated from theBeginOperationNamemethod- Passing other
IAsyncResultobjects is undefined. - Calling
EndOperationNamemultiple times with the sameIAsyncResultobject 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
IsCompletedperiodically, then callEndOperationNamewhen 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
EndOperationNamefrom the app’s main thread. This blocks execution until the op is complete. - Use the
AsyncWaitHandleto 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);