2012-03-07 57 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