WaitAny Method (Task[])
Collapse the table of content
Expand the table of content

Task.WaitAny Method (Task())

 

Waits for any of the provided Task objects to complete execution.

Namespace:   System.Threading.Tasks
Assembly:  mscorlib (in mscorlib.dll)

Public Shared Function WaitAny (
	ParamArray tasks As Task()
) As Integer

Parameters

tasks
Type: System.Threading.Tasks.Task()

An array of Task instances on which to wait.

Return Value

Type: System.Int32

The index of the completed Task object in the tasks array.

Exception Condition
ObjectDisposedException

The Task has been disposed.

ArgumentNullException

The tasks argument is null.

ArgumentException

The tasks argument contains a null element.

The following example launches five tasks, each of which sleeps for a minimum of 50 milliseconds or a maximum of 1,050 milliseconds. The WaitAny method then waits for any of the tasks to complete. The example displays the task ID of the task that ended the wait, as well as the current status of all the tasks.

Imports System.Threading
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      Dim tasks(4) As Task
      For ctr As Integer = 0 To 4
         Dim factor As Integer = ctr
         tasks(ctr) = Task.Run(Sub() Thread.Sleep(factor * 250 + 50))
      Next
      Dim index As Integer = Task.WaitAny(tasks)

      Console.WriteLine("Wait ended because task #{0} completed.",
                        tasks(index).Id)
      Console.WriteLine()
      Console.WriteLine("Current Status of Tasks:")
      For Each t In tasks
         Console.WriteLine("   Task {0}: {1}", t.Id, t.Status)
      Next
   End Sub
End Module
' The example displays output like the following:
'       Wait ended because task #1 completed.
'
'       Current Status of Tasks:
'          Task 1: RanToCompletion
'          Task 2: Running
'          Task 3: Running
'          Task 4: Running
'          Task 5: Running

Universal Windows Platform
Available since 4.5
.NET Framework
Available since 4.0
Portable Class Library
Supported in: portable .NET platforms
Silverlight
Available since 5.0
Windows Phone Silverlight
Available since 8.0
Windows Phone
Available since 8.1
Return to top
Show:
© 2016 Microsoft