Wait for One of Many Asynchronous Calls to Complete

Problem

You want to call multiple procedures asynchronously and suspend processing until any one call completes.

Solution

Retrieve the WaitHandle for each call, and use the shared WaitHandle.WaitAny method.

Discussion

The System.Threading.WaitHandle class provides a WaitAny method that accepts an array of WaitHandle objects and blocks until at least one WaitHandle is completed. When WaitAny returns, it provides an index number that indicates the position of the completed WaitHandle in the array.

The following example launches three calls at once. It then waits until at least one call finishes, displays the results, and then resumes waiting for one of the next two calls to complete. It uses an ArrayList ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.