C # IAsyncResult WaitAll - PullRequest
       15

C # IAsyncResult WaitAll

1 голос
/ 12 апреля 2011

В некоторых реализациях 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 один из вызовов завершится?

С уважением, Дананай

1 Ответ

6 голосов
/ 12 апреля 2011

Имеет смысл для меня.

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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...