C# System.Threading.Tasks.Task

Posted by saadlive on Sat, 26 Feb 2022 04:49:07 +0100

Task class

definition

Namespace:

System.Threading.Tasks

Assembly:

mscorlib.dll, netstandard.dll

Represents an asynchronous operation.

inherit

Object

Task

derive

System.Threading.Tasks.Task<TResult>

realization

IAsyncResult

annotation

Task Class represents a single operation that does not return a value and is typically performed asynchronously.   Task The object is in NET Framework 4 Task based asynchronous mode One of the central components of. Work performed by object Task It is usually executed asynchronously on the thread of the thread pool, rather than synchronously on the main application thread, so it can be used Status Properties and IsCanceled , IsCompleted And IsFaulted Property to determine the status of the task. Typically, lambda expressions are used to specify the work to be performed by a task.

For operations that return values, use Task<TResult> Class.

Contents of this part:

Task instantiation example
Create and execute tasks
Separate task creation and execution
Waiting for one or more tasks to complete
Mission and regional
For debugger developers

Task instantiation

The following example creates and performs four tasks. Three task execution Action<T> Delegate action named, which accepts parameters of type Object  . The fourth task executes a lambda expression( Action Delegate), which is defined inline in the call to the task creation method. Each task is instantiated and run in different ways:

  • Task t1 # is instantiated by calling the task class constructor, but Start() Only after a task is started can it start t2{T2 by calling its methods.

  • t2 instantiates and starts a task in a single method call by calling a method TaskFactory.StartNew(Action<Object>, Object) .

  • t3 instantiates and starts a task in a single method call by calling a method Run(Action) .

  • t4 executes tasks synchronously on the main thread by calling methods RunSynchronously() .

Since the task executes in a {t4# synchronous manner, it executes on the main application thread. The remaining tasks are typically performed asynchronously on one or more thread pool threads.

C # replication

using System;
using System.Threading;
using System.Threading.Tasks;

class Example
{
    static void Main()
    {
        Action<object> action = (object obj) =>
                                {
                                   Console.WriteLine("Task={0}, obj={1}, Thread={2}",
                                   Task.CurrentId, obj,
                                   Thread.CurrentThread.ManagedThreadId);
                                };

        // Create a task but do not start it.
        Task t1 = new Task(action, "alpha");

        // Construct a started task
        Task t2 = Task.Factory.StartNew(action, "beta");
        // Block the main thread to demonstrate that t2 is executing
        t2.Wait();

        // Launch t1 
        t1.Start();
        Console.WriteLine("t1 has been launched. (Main Thread={0})",
                          Thread.CurrentThread.ManagedThreadId);
        // Wait for the task to finish.
        t1.Wait();

        // Construct a started task using Task.Run.
        String taskData = "delta";
        Task t3 = Task.Run( () => {Console.WriteLine("Task={0}, obj={1}, Thread={2}",
                                                     Task.CurrentId, taskData,
                                                      Thread.CurrentThread.ManagedThreadId);
                                   });
        // Wait for the task to finish.
        t3.Wait();

        // Construct an unstarted task
        Task t4 = new Task(action, "gamma");
        // Run it synchronously
        t4.RunSynchronously();
        // Although the task was run synchronously, it is a good practice
        // to wait for it in the event exceptions were thrown by the task.
        t4.Wait();
    }
}
// The example displays output like the following:
//       Task=1, obj=beta, Thread=3
//       t1 has been launched. (Main Thread=1)
//       Task=2, obj=alpha, Thread=4
//       Task=3, obj=delta, Thread=3
//       Task=4, obj=gamma, Thread=1

Create and execute tasks

Task You can create instances in a variety of ways. From NET Framework 4.5, the most common method is to call static Run Method.   Run Method provides a simple way to start a task with default values without additional parameters. The following example uses Run(Action) Method to start the task, which will loop and display the number of loop iterations:

C # replication

using System;
using System.Threading.Tasks;

public class Example
{
   public static async Task Main()
   {
      await Task.Run( () => {
                                  // Just loop.
                                  int ctr = 0;
                                  for (ctr = 0; ctr <= 1000000; ctr++)
                                  {}
                                  Console.WriteLine("Finished {0} loop iterations",
                                                    ctr);
                               } );
   }
}
// The example displays the following output:
//        Finished 1000001 loop iterations

Another way is to do it in The most common way to start a task in. NET Framework 4 is static TaskFactory.StartNew Method.   Task.Factory Property return TaskFactory Object. Overloading of methods TaskFactory.StartNew Enables you to specify the parameters to be passed to the task creation options and task scheduler. The following example uses TaskFactory.StartNew Method to start the task. It is functionally equivalent to the code in the previous example.

C # replication

using System;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      Task t = Task.Factory.StartNew( () => {
                                  // Just loop.
                                  int ctr = 0;
                                  for (ctr = 0; ctr <= 1000000; ctr++)
                                  {}
                                  Console.WriteLine("Finished {0} loop iterations",
                                                    ctr);
                               } );
      t.Wait();
   }
}
// The example displays the following output:
//        Finished 1000001 loop iterations

For a more complete example, see Task based asynchronous programming.

Separate task creation and execution

Task Class also provides a constructor to initialize the task, but the task is not scheduled to execute. For performance reasons Task.Run Or TaskFactory.StartNew Method is the preferred mechanism for creating and planning computing tasks, but for situations that must be separated from creation and planning, constructors can be used and then called. Task.Start Method to plan the task to be executed later.

Waiting for one or more tasks to complete

Because tasks usually run asynchronously on thread pool threads, the thread that creates and starts the task will continue to execute immediately after instantiating the task. In some cases, when the calling thread is the main application thread, the application may terminate before the task actually starts executing. In other cases, the logic of the application may require the calling thread to continue when one or more tasks have completed execution. You can call the Wait method to Wait for one or more tasks to complete, so as to synchronize the execution of the calling thread and the asynchronous tasks it starts.

To wait for a single task to complete, you can call its Task.Wait Method. A call to a method will Wait Block the calling thread until the single class instance is executed.

The following example calls with no parameters Wait() Method waits unconditionally until the task is completed. Task by calling Thread.Sleep Method to simulate a two second operation.

C # replication

using System;   
using System.Threading;
using System.Threading.Tasks;

class Program
{
    static Random rand = new Random();

    static void Main()
    {
        // Wait on a single task with no timeout specified.
        Task taskA = Task.Run( () => Thread.Sleep(2000));
        Console.WriteLine("taskA Status: {0}", taskA.Status);
        try {
          taskA.Wait();
          Console.WriteLine("taskA Status: {0}", taskA.Status);
       } 
       catch (AggregateException) {
          Console.WriteLine("Exception in taskA.");
       }   
    }    
}
// The example displays output like the following:
//     taskA Status: WaitingToRun
//     taskA Status: RanToCompletion

You can also conditionally wait for the task to be completed.   Wait(Int32) And Wait(TimeSpan) Method blocks the calling thread until the task completes or the timeout interval, whichever occurs first. Since the following example starts a task with a sleep time of two seconds, but defines a timeout value of one second, the calling thread will block until the timeout expires and the task has completed execution.

C # replication

using System;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      // Wait on a single task with a timeout specified.
      Task taskA = Task.Run( () => Thread.Sleep(2000));
      try {
        taskA.Wait(1000);       // Wait for 1 second.
        bool completed = taskA.IsCompleted;
        Console.WriteLine("Task A completed: {0}, Status: {1}",
                         completed, taskA.Status);
        if (! completed)
           Console.WriteLine("Timed out before task A completed.");                 
       }
       catch (AggregateException) {
          Console.WriteLine("Exception in taskA.");
       }   
   }
}
// The example displays output like the following:
//     Task A completed: False, Status: Running
//     Timed out before task A completed.

You can also provide unmarking by calling and methods Wait(CancellationToken) Wait(Int32, CancellationToken)  . If in IsCancellationRequested True - when the method is executed, the attribute of the tag is or true Wait , the method raises OperationCanceledException .

In some cases, you may need to wait for the first of a series of ongoing tasks to be completed, but don't care which task is. To do this, you can call one of the overloads of the method Task.WaitAny  . The following example creates three tasks, each sleeping at an interval determined by the random number generator.   WaitAny(Task[]) Method waits for the first task to complete. The example then displays status information for all three tasks.

C # replication

using System;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      var tasks = new Task[3];
      var rnd = new Random();
      for (int ctr = 0; ctr <= 2; ctr++)
         tasks[ctr] = Task.Run( () => Thread.Sleep(rnd.Next(500, 3000)));

      try {
         int index = Task.WaitAny(tasks);
         Console.WriteLine("Task #{0} completed first.\n", tasks[index].Id);
         Console.WriteLine("Status of all tasks:");
         foreach (var t in tasks)
            Console.WriteLine("   Task #{0}: {1}", t.Id, t.Status);
      }
      catch (AggregateException) {
         Console.WriteLine("An exception occurred.");
      }
   }
}
// The example displays output like the following:
//     Task #1 completed first.
//     
//     Status of all tasks:
//        Task #3: Running
//        Task #1: RanToCompletion
//        Task #4: Running

You can also wait for a series of tasks to be completed by calling methods WaitAll  . The following example creates ten tasks, waits for all ten tasks to complete, and then displays their status.

C # replication

using System;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      // Wait for all tasks to complete.
      Task[] tasks = new Task[10];
      for (int i = 0; i < 10; i++)
      {
          tasks[i] = Task.Run(() => Thread.Sleep(2000));
      }
      try {
         Task.WaitAll(tasks);
      }
      catch (AggregateException ae) {
         Console.WriteLine("One or more exceptions occurred: ");
         foreach (var ex in ae.Flatten().InnerExceptions)
            Console.WriteLine("   {0}", ex.Message);
      }   

      Console.WriteLine("Status of completed tasks:");
      foreach (var t in tasks)
         Console.WriteLine("   Task #{0}: {1}", t.Id, t.Status);
   }
}
// The example displays the following output:
//     Status of completed tasks:
//        Task #2: RanToCompletion
//        Task #1: RanToCompletion
//        Task #3: RanToCompletion
//        Task #4: RanToCompletion
//        Task #6: RanToCompletion
//        Task #5: RanToCompletion
//        Task #7: RanToCompletion
//        Task #8: RanToCompletion
//        Task #9: RanToCompletion
//        Task #10: RanToCompletion

Please note that when you Wait for one or more tasks to complete, any exception thrown in the running task will upload and broadcast {Wait in the thread calling the method, as shown in the following example. It starts 12 tasks, three of which are completed normally, and three tasks throw exceptions. The remaining six tasks will be cancelled before starting and three tasks will be cancelled during execution. Abnormal in WaitAll Raised in a method call and processed by the # try / catch # block.

C # replication

using System;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      // Create a cancellation token and cancel it.
      var source1 = new CancellationTokenSource();
      var token1 = source1.Token;
      source1.Cancel();
      // Create a cancellation token for later cancellation.
      var source2 = new CancellationTokenSource();
      var token2 = source2.Token;
       
      // Create a series of tasks that will complete, be cancelled, 
      // timeout, or throw an exception.
      Task[] tasks = new Task[12];
      for (int i = 0; i < 12; i++)
      {
          switch (i % 4) 
          {
             // Task should run to completion.
             case 0:
                tasks[i] = Task.Run(() => Thread.Sleep(2000));
                break;
             // Task should be set to canceled state.
             case 1:   
                tasks[i] = Task.Run( () => Thread.Sleep(2000),
                         token1);
                break;         
             case 2:
                // Task should throw an exception.
                tasks[i] = Task.Run( () => { throw new NotSupportedException(); } );
                break;
             case 3:
                // Task should examine cancellation token.
                tasks[i] = Task.Run( () => { Thread.Sleep(2000); 
                                             if (token2.IsCancellationRequested)
                                                token2.ThrowIfCancellationRequested();
                                             Thread.Sleep(500); }, token2);   
                break;
          }
      }
      Thread.Sleep(250);
      source2.Cancel();
       
      try {
         Task.WaitAll(tasks);
      }
      catch (AggregateException ae) {
          Console.WriteLine("One or more exceptions occurred:");
          foreach (var ex in ae.InnerExceptions)
             Console.WriteLine("   {0}: {1}", ex.GetType().Name, ex.Message);
       }   

      Console.WriteLine("\nStatus of tasks:");
      foreach (var t in tasks) {
         Console.WriteLine("   Task #{0}: {1}", t.Id, t.Status);
         if (t.Exception != null) {
            foreach (var ex in t.Exception.InnerExceptions)
               Console.WriteLine("      {0}: {1}", ex.GetType().Name,
                                 ex.Message);
         }
      }
   }
}
// The example displays output like the following:
//   One or more exceptions occurred:
//      TaskCanceledException: A task was canceled.
//      NotSupportedException: Specified method is not supported.
//      TaskCanceledException: A task was canceled.
//      TaskCanceledException: A task was canceled.
//      NotSupportedException: Specified method is not supported.
//      TaskCanceledException: A task was canceled.
//      TaskCanceledException: A task was canceled.
//      NotSupportedException: Specified method is not supported.
//      TaskCanceledException: A task was canceled.
//   
//   Status of tasks:
//      Task #13: RanToCompletion
//      Task #1: Canceled
//      Task #3: Faulted
//         NotSupportedException: Specified method is not supported.
//      Task #8: Canceled
//      Task #14: RanToCompletion
//      Task #4: Canceled
//      Task #6: Faulted
//         NotSupportedException: Specified method is not supported.
//      Task #7: Canceled
//      Task #15: RanToCompletion
//      Task #9: Canceled
//      Task #11: Faulted
//         NotSupportedException: Specified method is not supported.
//      Task #12: Canceled

For more information about exception handling in Task-based asynchronous operations, see exception handling.

Mission and regional

From face to face NET Framework 4.6, the culture of the thread that creates and invokes the task will become part of the thread context. That is, regardless of the current culture of the thread executing the task, the current culture of the task is the culture of the calling thread. For the target NET Framework before 4.6 NET Framework version, the culture of the task is the culture of the thread executing the task. For more information, see the section "culture and task-based asynchronous operations" in the topic CultureInfo .

Remarks

Store apps follow the Windows runtime settings and get the default culture.

For debugger developers

For developers who implement custom debuggers, multiple internal and private members of a task can be useful (they may change due to Publishing). This value is , M_ The taskid} field acts as a back-up store for attributes Id However, it may be more efficient to access this field directly from the debugger instead of accessing the next available ID of the same value (s_taskIdCounter uses the counter to retrieve the task) through the getter method of the property. Similarly, M_ The stateflags field stores information about the current life cycle stage of the task, which can also be accessed through properties Status  .  m_ The action field stores a reference to the delegate of the task, and m_ The stateobject field stores the asynchronous state that the developer passes to the task. Finally, for debuggers that analyze stack frames, the {InternalWait} method provides possible markers when a task enters a wait operation.

Constructor

Constructor
Task(Action)

Initializes a new with the specified action Task.

Task(Action, CancellationToken)

Use specified actions and Task Initialize new CancellationToken.

Task(Action, CancellationToken, TaskCreationOptions)

Initializes a new with the specified action and creation options Task.

Task(Action, TaskCreationOptions)

Initializes a new with the specified action and creation options Task.

Task(Action<Object>, Object)

Initializes a new with the specified action and state Task.

Task(Action<Object>, Object, CancellationToken)

Initializes a new with the specified actions, States, and options Task.

Task(Action<Object>, Object, CancellationToken, TaskCreationOptions)

Initializes a new with the specified actions, States, and options Task.

Task(Action<Object>, Object, TaskCreationOptions)

Initializes a new with the specified actions, States, and options Task.

attribute

attribute
AsyncState

Get created at Task The status object provided during the. If not provided, it will be null.

CompletedTask

Get a successfully completed task.

CreationOptions

Gets the name used to create this task TaskCreationOptions.

CurrentId

Returns the current execution Task ID of the.

Exception

Acquisition leads AggregateException Early ending Task . If Task Successfully completed or no exception has been thrown, which will return null.

Factory

Provides information for creating and configuring Task And Task<TResult> Access to the factory method of the instance.

Id

Get this Task ID of the instance.

IsCanceled

Get this Task Whether the instance has completed execution due to cancellation.

IsCompleted

Gets a value indicating whether the task has been completed.

IsCompletedSuccessfully

Know whether the task runs to completion.

IsFaulted

Get Task Whether it is completed due to an unhandled exception.

Status

Get the for this task TaskStatus.

method

method
ConfigureAwait(Boolean)

Configure to wait for this Task awaiter.

ContinueWith(Action<Task,Object>, Object)

Create a target Task Upon completion, receive the status information provided by the caller and execute the continuation task.

ContinueWith(Action<Task,Object>, Object, CancellationToken)

Create a target Task Upon completion, receive the status information and unmark provided by the caller, and execute the continuation task asynchronously.

ContinueWith(Action<Task,Object>, Object, CancellationToken, TaskContinuationOptions, TaskScheduler)

Create a target Task Upon completion, receive the status information provided by the caller and unmark and execute the continuation task. The continuation task is executed according to a specified set of conditions and uses the specified scheduler.

ContinueWith(Action<Task,Object>, Object, TaskContinuationOptions)

Create a target Task Upon completion, receive the status information provided by the caller and execute the continuation task. The continuation task is performed according to a set of specified conditions.

ContinueWith(Action<Task,Object>, Object, TaskScheduler)

Create a target Task A continuation task that receives the status information provided by the caller and executes asynchronously upon completion. The continuation task uses the specified scheduler.

ContinueWith(Action<Task>)

Create a target Task A continuation task that is executed asynchronously on completion.

ContinueWith(Action<Task>, CancellationToken)

Create a target Task On completion, a continuation task that is unmarked and executed asynchronously can be received.

ContinueWith(Action<Task>, CancellationToken, TaskContinuationOptions, TaskScheduler)

Create one that follows the specified when the target task is completed TaskContinuationOptions Continuing tasks performed. The continuation task receives a cancel flag and uses the specified scheduler.

ContinueWith(Action<Task>, TaskContinuationOptions)

Create one that follows the specified when the target task is completed TaskContinuationOptions Continuing tasks performed.

ContinueWith(Action<Task>, TaskScheduler)

Create a target Task A continuation task that is executed asynchronously on completion. The continuation task uses the specified scheduler.

ContinueWith<TResult>(Func<Task,Object,TResult>, Object)

Create a target Task A continuation task that receives the status information provided by the caller and executes asynchronously when a value is completed and returned.

ContinueWith<TResult>(Func<Task,Object,TResult>, Object, CancellationToken)

Create a target Task Returns a value when the task is completed asynchronously. The continuation task receives the status information and unmark provided by the caller.

ContinueWith<TResult>(Func<Task,Object,TResult>, Object, CancellationToken, TaskContinuationOptions, TaskScheduler)

Create a target Task The continuation task executed according to the specified task continuation option when completing and returning a value. The continuation task receives the status information and unmark provided by the caller and uses the specified scheduler.

ContinueWith<TResult>(Func<Task,Object,TResult>, Object, TaskContinuationOptions)

Create a target Task A continuation task executed according to the specified task continuation option when completed. The continuation task receives the status information provided by the caller.

ContinueWith<TResult>(Func<Task,Object,TResult>, Object, TaskScheduler)

Create a target Task A continuation task that is executed asynchronously on completion. The continuation task receives the status information provided by the caller and uses the specified scheduler.

ContinueWith<TResult>(Func<Task,TResult>)

Create a target Task<TResult> A continuation task that executes asynchronously and returns a value on completion.

ContinueWith<TResult>(Func<Task,TResult>, CancellationToken)

Create a target Task A continuation task that executes asynchronously and returns a value on completion. The continuation task received a cancel flag.

ContinueWith<TResult>(Func<Task,TResult>, CancellationToken, TaskContinuationOptions, TaskScheduler)

Create a continuation task that executes according to the specified continuation task option and returns a value. The continuation task is passed in a unmark and uses the specified scheduler.

ContinueWith<TResult>(Func<Task,TResult>, TaskContinuationOptions)

Create a continuation task that executes according to the specified continuation task option and returns a value.

ContinueWith<TResult>(Func<Task,TResult>, TaskScheduler)

Create a target Task A continuation task that executes asynchronously and returns a value on completion. The continuation task uses the specified scheduler.

Delay(Int32)

Creates a task that completes after a specified number of milliseconds.

Delay(Int32, CancellationToken)

Creates a cancelable task that completes after a specified number of milliseconds.

Delay(TimeSpan)

Create a task that is completed after a specified time interval.

Delay(TimeSpan, CancellationToken)

Creates a cancelable task that completes after a specified time interval.

Dispose()

Release Task All resources used by the current instance of the class.

Dispose(Boolean)

Release Task And release all its unmanaged resources at the same time.

Equals(Object)

Determines whether the specified object is equal to the current object.

(inherited from) Object)
FromCanceled(CancellationToken)

Create Task , which is completed due to the cancellation operation performed by the specified cancellation flag.

FromCanceled<TResult>(CancellationToken)

Create Task<TResult> , which is completed due to the cancellation operation performed by the specified cancellation flag.

FromException(Exception)

Create Task , it has the specified exception after completion.

FromException<TResult>(Exception)

Create Task<TResult> , it has the specified exception after completion.

FromResult<TResult>(TResult)

Creates a successfully completed for the specified result Task<TResult>.

GetAwaiter()

Gets the name used to wait for this Task awaiter.

GetHashCode()

As the default hash function.

(inherited from) Object)
GetType()

Gets the of the current instance Type.

(inherited from) Object)
MemberwiseClone()

Create current Object Shallow copy of.

(inherited from) Object)
Run(Action)

Queue the specified work running on the thread pool and return the information representing the work Task Object.

Run(Action, CancellationToken)

Queue the specified work running on the thread pool and return the information representing the work Task Object. You can use the cancel flag to cancel the work if it has not been started.

Run(Func<Task>)

Queue the specified work running on the thread pool and return the proxy item of the task returned by {function}.

Run(Func<Task>, CancellationToken)

Queue the specified work running on the thread pool and return the proxy item of the task returned by {function}. You can use the cancel flag to cancel the work if it has not been started.

Run<TResult>(Func<Task<TResult>>)

Queue the specified work to run on the process pool and return the agent of the Task(TResult) returned by the function. You can use the cancel flag to cancel the work if it has not been started.

Run<TResult>(Func<Task<TResult>>, CancellationToken)

Queue the specified work to run on the process pool and return the agent of the Task(TResult) returned by the function.

Run<TResult>(Func<TResult>)

Queue the specified work running on the thread pool and return the information representing the work Task<TResult> Object. You can use the cancel flag to cancel the work if it has not been started.

Run<TResult>(Func<TResult>, CancellationToken)

Queue the specified work running on the process pool and return the Task(TResult) object representing the work.

RunSynchronously()

For the current Task Synchronous operation TaskScheduler.

RunSynchronously(TaskScheduler)

To provide Task Synchronous operation TaskScheduler.

Start()

Start Task And schedule it to the current TaskScheduler Execute in.

Start(TaskScheduler)

Start Task And arrange it to the designated location TaskScheduler Execute in.

ToString()

Returns a string representing the current object.

(inherited from) Object)
Wait()

Wait Task Complete the execution process.

Wait(CancellationToken)

Wait Task Complete the execution process. If the unmark is cancelled before the task is completed, the wait will terminate.

Wait(Int32)

Wait Task Execution completed within the specified number of milliseconds.

Wait(Int32, CancellationToken)

Wait Task Complete the execution process. If the timeout interval ends or the unmark is cancelled before the task is completed, the wait will terminate.

Wait(TimeSpan)

Wait Task The execution is completed within the specified time interval.

WaitAll(Task[])

All waiting to be provided Task Object completes the execution process.

WaitAll(Task[], CancellationToken)

All waiting to be provided Task Object completes the execution process (unless the wait is cancelled).

WaitAll(Task[], Int32)

Waiting for all offers Task Execution completed within the specified number of milliseconds.

WaitAll(Task[], Int32, CancellationToken)

All waiting to be provided Task Object completes execution within the specified number of milliseconds, or waits until the wait is cancelled.

WaitAll(Task[], TimeSpan)

Wait for all offers to be cancelled Task Object completes execution within the specified time interval.

WaitAny(Task[])

Any information waiting to be provided Task Object completes the execution process.

WaitAny(Task[], CancellationToken)

Any information waiting to be provided Task Object completes the execution process (unless the wait is cancelled).

WaitAny(Task[], Int32)

Waiting for any offers Task Object completed execution within the specified number of milliseconds.

WaitAny(Task[], Int32, CancellationToken)

Any information waiting to be provided Task Object completes execution within the specified number of milliseconds, or waits until unmarked.

WaitAny(Task[], TimeSpan)

Waiting for any offers Task Object completes execution within the specified time interval.

WhenAll(IEnumerable<Task>)

Create a task that will all in the enumerable collection Task When all objects have completed.

WhenAll(Task[])

Create a task that will be all in the array Task When all objects have completed.

WhenAll<TResult>(IEnumerable<Task<TResult>>)

Create a task that will all in the enumerable collection Task<TResult> When all objects have completed.

WhenAll<TResult>(Task<TResult>[])

Create a task that will be all in the array Task<TResult> When all objects have completed.

WhenAny(IEnumerable<Task>)

Create a task that will be completed when any provided task has been completed.

WhenAny(Task, Task)

When any of the tasks provided are completed, create a task that will be completed.

WhenAny(Task[])

Create a task that will be completed when any provided task has been completed.

WhenAny<TResult>(IEnumerable<Task<TResult>>)

Create a task that will be completed when any provided task has been completed.

WhenAny<TResult>(Task<TResult>, Task<TResult>)

When any of the tasks provided are completed, create a task that will be completed.

WhenAny<TResult>(Task<TResult>[])

Create a task that will be completed when any provided task has been completed.

Yield()

Create a waiting task that asynchronously generates the current context.

Explicit interface implementation

Explicit interface implementation
IAsyncResult.AsyncWaitHandle

Gets the available to wait for the task to complete WaitHandle.

IAsyncResult.CompletedSynchronously

Gets an indication of whether the operation has been synchronized.

Extension method

Extension method
DispatcherOperationWait(Task)

Wait indefinitely to complete the foundation DispatcherOperation.

DispatcherOperationWait(Task, TimeSpan)

Waiting basis DispatcherOperation Complete until the specified required time is reached.

IsDispatcherOperationTask(Task)

Returns a value indicating the Task Whether with DispatcherOperation Relevant.

Apply to

Apply to
productedition
.NETCore 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6
.NET Framework4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8
.NET Standard1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP10.0
Xamarin.iOS10.8
Xamarin.Mac3.0

Thread safety

All members except Task Dispose() Are thread safe and can be used from multiple threads at the same time.

See also

Topics: C# linq p2p