How is the IsCompleted property of the IAsyncResult updated?
When I call the method asynchronously (using the BeginXxx / EndXxx template), I get the result IAsyncResult
after calling BeginXxx. How is the "isCompleted" property (in the returned result variable) updated if neither the BeginXxxx method nor EndXxx has a reference to the result variable?
Example:
// Create the delegate.
AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod);
// Initiate the asychronous call.
IAsyncResult result = caller.BeginInvoke(3000, out threadId, null, null);
// Poll while simulating work.
while(result.IsCompleted == false) {
Thread.Sleep(250);
Console.Write(".");
}
+3
source to share
1 answer
BeginInvoke
returns to you IAsyncResult
, so it will refer to it. This will be internally generated and sent back to you.
For example, BeginRead
in FileStream creates FileStreamAsyncResult
and then returns it:
private unsafe FileStreamAsyncResult BeginReadCore(byte[] bytes, int offset, int numBytes, AsyncCallback userCallback, object stateObject, int numBufferedBytesRead)
{
NativeOverlapped* overlappedPtr;
FileStreamAsyncResult ar = new FileStreamAsyncResult {
_handle = this._handle,
_userCallback = userCallback,
_userStateObject = stateObject,
_isWrite = false,
_numBufferedBytes = numBufferedBytesRead
};
ManualResetEvent event2 = new ManualResetEvent(false);
ar._waitHandle = event2;
.....
if (hr == 0x6d)
{
overlappedPtr->InternalLow = IntPtr.Zero;
ar.CallUserCallback();
return ar;
}
+2
source to share