Two questions on ensuring EndInvoke() gets called on a list of IAsyncResult objects

Posted by RobV on Stack Overflow See other posts from Stack Overflow or by RobV
Published on 2010-06-14T11:45:00Z Indexed on 2010/06/14 11:52 UTC
Read the original article Hit count: 260

Filed under:
|
|

So this question is regarding the .Net IAsyncResult design pattern and the necessity of calling EndInvoke as covered in this question

Background

I have some code where I'm firing off potentially many asynchronous calls to a particular function and then waiting for all these calls to finish before using EndInvoke() to get back all the results.

Question 1

I don't know whether any of the calls has encountered an exception until I call EndInvoke() and in the event that an exception occurs in one of the calls the entire method should fail and the exception gets wrapped into an API specific exception and thrown upwards.

So my first question is what's the best way then to ensure that the remainder of the async calls get properly terminated?

Is a finally block which calls EndInvoke() on the remainder of the unterminated calls (and ignores any further exceptions) the best way to do this?

Question 2

Secondly when I first fire off all my asyc calls I then call WaitHandle.WaitAll() on the array of WaitHandle instances that I've got from my IAsyncResult instances. The method which is firing all these async calls has a timeout to adhere to so I provide this to the WaitAll() method. Then I test whether all the calls have completed, if not then the timeout must have been reached so the method should also fail and throw another API specific exception.

So my second question is what should I do in this case?

I need to call EndInvoke() to terminate all these async calls before I throw the error but at the same time I don't want the code to get stuck since EndInvoke() is blocking. In theory at least if the WaitAll() call times out then all the async calls should themselves have timed out and thrown exceptions (thus completing the call) since they are also governed by a timeout but this timeout is potentially different from the main timeout

© Stack Overflow or respective owner

Related posts about .NET

Related posts about async