如何更新IAsyncResult的属性是否已完成?

时间:2012-03-07 15:05:29

标签: c# asp.net asynchronous

当我异步调用方法时(使用模式BeginXxx / EndXxx),在调用BeginXxx后得到IAsyncResult结果。如果方法BeginXxxx或EndXxx都没有对结果变量的引用,那么属性“isCompleted”(在返回的结果变量中)如何得到更新?

例如:

// 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(".");
}

1 个答案:

答案 0 :(得分:2)

BeginInvoke正在向您返回IAsyncResult,因此它会引用它。这将在内部创建并发回给您。

例如,FileStream中的BeginRead创建FileStreamAsyncResult然后返回它:

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;
    }