2012-03-07 38 views
3

当我异步调用方法(使用BeginXxx/EndXxx模式)时,调用BeginXxx后得到IAsyncResult结果。如果方法BeginXxxx或EndXxx对结果变量没有任何引用,那么属性“isCompleted”(在返回结果变量中)如何得到更新?如何更新IAsyncResult的属性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("."); 
} 

回答

2

BeginInvoke正在返回你的IAsyncResult所以必须对它的引用。这将在内部创建并发回给您。

例如,BeginRead中的FileStream创建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; 
    } 
+0

确定。这说得通。所以这个引用是通过XxxxEnd传递的,它将isCompleted属性更改为false。谢谢... – outlookrperson 2012-03-08 14:06:09