C# IAsyncResult WaitAll

余生颓废 提交于 2019-12-23 03:51:46

问题


In some of the implementations 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


回答1:


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.



来源:https://stackoverflow.com/questions/5629811/c-sharp-iasyncresult-waitall

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!