C#IAsyncResult WaitAll

在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

我感觉合理。

 // 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之前完成,您将需要考虑程序需要执行的操作。