开发者

C# IAsyncResult WaitAll

开发者 https://www.devze.com 2023-02-23 15:02 出处:网络
In some of the implementation开发者_JAVA技巧s of WaitAll I have seen the following code IAsyncResult result1 = Method.BeginInvoke(10, MyCallback, null)

In some of the implementation开发者_JAVA技巧s of WaitAll I have seen the following code

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)

Does this seem right ? What are the chances that before the waitHandles array is created one of the calls complete ?

Regards, Dhananjay


Makes sense to me.

// 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.

What exactly do you find odd?

Asking "what are the chances" is a bad sign. The chances are it might happen which means you will need to account for what the program needs to do if and when the methods complete before you WaitAll.

0

精彩评论

暂无评论...
验证码 换一张
取 消