2011-04-12 70 views
1

在一些了WaitAll的實現我看到下面的代碼C#的IAsyncResult爲WaitAll

IAsyncResult result1 = Method.BeginInvoke(10, MyCallback, null) 
IAsyncResult result2 = Method.BeginInvoke(20, MyCallback, null) 
WaitHandle[] waitHandles = new WaitHandle[] { result1.AsyncWaitHandle, result2.AsyncWaitHandle}; 
WaitHandle.WaitAll(waitHandles) 

這看起來對嗎?在創建waitHandles數組之前,其中一個調用完成之後有什麼機會?

問候, Dhananjay

回答

6

對我來說很有意義。

// Begin invoking the first and second method, and give them a callback 
IAsyncResult result1 = Method.BeginInvoke(10, MyCallback, null) 
IAsyncResult result2 = Method.BeginInvoke(20, MyCallback, null) 

// Any time past the point of invokation, MyCallback could be called. 
// Get the wait handles of the async results, regardless of whether they have finished or not 
WaitHandle[] waitHandles = new WaitHandle[] { result1.AsyncWaitHandle, result2.AsyncWaitHandle}; 

// Make sure to wait until the methods have finished. 
// They could have finished immediately, and MyCallback could have already been called, 
// but we will never get past this line unless they have finished. 
WaitHandle.WaitAll(waitHandles) 
// We may have waited on the function to finish, or they may have been done before we arrived at the previous line. Either way, they are done now. 

你究竟發現了什麼奇怪的東西?

問「有什麼機會」是一個不好的跡象。機會是它可能發生這意味着如果在WaitAll之前完成這些方法,您需要說明該程序需要做什麼。

+0

原因是var result = del.EndInvoke(ar); – user489686 2011-04-12 11:34:47

+0

EndInvoke也等待異步結果結束,但回調在到達EndInvoke之前可能仍然被調用。 – 2011-04-12 14:02:32