This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Note
Access to this page requires authorization. You can trysigning in orchanging directories.
Access to this page requires authorization. You can trychanging directories.
Important
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
Represents an asynchronous operation that can return a value.
generic <typename TResult>public ref class Task : System::Threading::Tasks::Task
public class Task<TResult> : System.Threading.Tasks.Task
type Task<'Result> = class inherit Task
Public Class Task(Of TResult)Inherits Task
The type of the result produced by thisTask<TResult>.
TheTask<TResult> class represents a single operation that returns a value and that usually executes asynchronously.Task<TResult> objects are one of the central components of thetask-based asynchronous pattern first introduced in .NET Framework 4. Because the work performed by aTask<TResult> object typically executes asynchronously on a thread pool thread rather than synchronously on the main application thread, you can use theStatus property, as well as theIsCanceled,IsCompleted, andIsFaulted properties, to determine the state of a task. Most commonly, a lambda expression is used to specify the work that the task is to perform.
Task<TResult> instances may be created in a variety of ways. The most common approach, which is available starting with .NET Framework 4.5, is to call the staticTask.Run<TResult>(Func<TResult>) orTask.Run<TResult>(Func<TResult>, CancellationToken) method. These methods provide a simple way to start a task by using default values and without acquiring additional parameters. The following example uses theTask.Run<TResult>(Func<TResult>) method to start a task that loops and then displays the number of loop iterations:
using System;using System.Threading.Tasks;public class Example{ public static void Main() { var t = Task<int>.Run( () => { // Just loop. int max = 1000000; int ctr = 0; for (ctr = 0; ctr <= max; ctr++) { if (ctr == max / 2 && DateTime.Now.Hour <= 12) { ctr++; break; } } return ctr; } ); Console.WriteLine("Finished {0:N0} iterations.", t.Result); }}// The example displays output like the following:// Finished 1,000,001 loop iterations.
Imports System.Threading.TasksModule Example Public Sub Main() Dim t As Task(Of Integer) = Task.Run(Function() Dim max As Integer = 1000000 Dim ctr As Integer For ctr = 0 to max If ctr = max \ 2 And Date.Now.Hour <= 12 Then ctr += 1 Exit For End If Next Return ctr End Function) Console.WriteLine("Finished {0:N0} iterations.", t.Result) End SubEnd Module' The example displays the following output:' Finished 1,000,001 loop iterations
An alternative, and the most common way to start a task in .NET Framework 4, is to call the staticTaskFactory.StartNew orTaskFactory<TResult>.StartNew method. TheTask.Factory property returns aTaskFactory object, and theTask<TResult>.Factory property returns aTaskFactory<TResult> object. Overloads of theirStartNew
method let you pass arguments, define task creation options, and specify a task scheduler. The following example uses theTaskFactory<TResult>.StartNew(Func<TResult>) method to start a task. It is functionally equivalent to the code in the previous example.
using System;using System.Threading.Tasks;public class Example{ public static void Main() { var t = Task<int>.Factory.StartNew( () => { // Just loop. int max = 1000000; int ctr = 0; for (ctr = 0; ctr <= max; ctr++) { if (ctr == max / 2 && DateTime.Now.Hour <= 12) { ctr++; break; } } return ctr; } ); Console.WriteLine("Finished {0:N0} iterations.", t.Result); }}// The example displays the following output:// Finished 1000001 loop iterations
Imports System.Threading.TasksModule Example Public Sub Main() Dim t = Task(Of Integer).Factory.StartNew(Function() Dim max As Integer = 1000000 Dim ctr As Integer For ctr = 0 to max If ctr = max \ 2 And Date.Now.Hour <= 12 Then ctr += 1 Exit For End If Next Return ctr End Function) Console.WriteLine("Finished {0:N0} iterations.", t.Result) End SubEnd Module' The example displays output like the following:' Finished 1,000,001 iterations
For more complete examples, seeTask-based Asynchronous Programming.
TheTask<TResult> class also provides constructors that initialize the task but that do not schedule it for execution. For performance reasons, theTask.Run andTask.Factory.StartNew
methods are the preferred mechanisms for creating and scheduling computational tasks, but for scenarios where task creation and scheduling must be separated, the constructors may be used, and the task'sStart method may then be used to schedule the task for execution at a later time.
Starting with desktop apps that target .NET Framework 4.6, the culture of the thread that creates and invokes a task becomes part of the thread's context. That is, regardless of the current culture of the thread on which the task executes, the current culture of the task is the culture of the calling thread. For apps that target versions of .NET Framework prior to .NET Framework 4.6, the culture of the task is the culture of the thread on which the task executes. For more information, see the "Culture and task-based asynchronous operations" section in theCultureInfo topic. Note that Store apps follow the Windows Runtime in setting and getting the default culture.
For operations that do not return a value, you use theTask class. Starting with C# 7.0, for a more lightweight task that is a value type rather than a reference type, use theSystem.Threading.Tasks.ValueTask<TResult> structure.
AsyncState | Gets the state object supplied when theTask was created, or null if none was supplied. (Inherited fromTask) |
CreationOptions | Gets theTaskCreationOptions used to create this task. (Inherited fromTask) |
Exception | Gets theAggregateException that caused theTask to end prematurely. If theTask completed successfully or has not yet thrown any exceptions, this will return |
Factory | Gets a factory method for creating and configuringTask<TResult> instances. |
Id | Gets an ID for thisTask instance. (Inherited fromTask) |
IsCanceled | Gets whether thisTask instance has completed execution due to being canceled. (Inherited fromTask) |
IsCompleted | Gets a value that indicates whether the task has completed. (Inherited fromTask) |
IsCompletedSuccessfully | Gets whether the task ran to completion. (Inherited fromTask) |
IsFaulted | Gets whether theTask completed due to an unhandled exception. (Inherited fromTask) |
Result | Gets the result value of thisTask<TResult>. |
Status | Gets theTaskStatus of this task. (Inherited fromTask) |
ConfigureAwait(Boolean) | Configures an awaiter used to await thisTask<TResult>. |
ConfigureAwait(ConfigureAwaitOptions) | Configures an awaiter used to await thisTask. |
ContinueWith(Action<Task,Object>, Object, CancellationToken, TaskContinuationOptions, TaskScheduler) | Creates a continuation that receives caller-supplied state information and a cancellation token and that executes when the targetTask completes. The continuation executes based on a set of specified conditions and uses a specified scheduler. (Inherited fromTask) |
ContinueWith(Action<Task,Object>, Object, CancellationToken) | Creates a continuation that receives caller-supplied state information and a cancellation token and that executes asynchronously when the targetTask completes. (Inherited fromTask) |
ContinueWith(Action<Task,Object>, Object, TaskContinuationOptions) | Creates a continuation that receives caller-supplied state information and executes when the targetTask completes. The continuation executes based on a set of specified conditions. (Inherited fromTask) |
ContinueWith(Action<Task,Object>, Object, TaskScheduler) | Creates a continuation that receives caller-supplied state information and executes asynchronously when the targetTask completes. The continuation uses a specified scheduler. (Inherited fromTask) |
ContinueWith(Action<Task,Object>, Object) | Creates a continuation that receives caller-supplied state information and executes when the targetTask completes. (Inherited fromTask) |
ContinueWith(Action<Task<TResult>,Object>, Object, CancellationToken, TaskContinuationOptions, TaskScheduler) | Creates a continuation that executes when the targetTask<TResult> completes. |
ContinueWith(Action<Task<TResult>,Object>, Object, CancellationToken) | Creates a continuation that executes when the targetTask<TResult> completes. |
ContinueWith(Action<Task<TResult>,Object>, Object, TaskContinuationOptions) | Creates a continuation that executes when the targetTask<TResult> completes. |
ContinueWith(Action<Task<TResult>,Object>, Object, TaskScheduler) | Creates a continuation that executes when the targetTask<TResult> completes. |
ContinueWith(Action<Task<TResult>,Object>, Object) | Creates a continuation that is passed state information and that executes when the targetTask<TResult> completes. |
ContinueWith(Action<Task<TResult>>, CancellationToken, TaskContinuationOptions, TaskScheduler) | Creates a continuation that executes according the condition specified in |
ContinueWith(Action<Task<TResult>>, CancellationToken) | Creates a cancelable continuation that executes asynchronously when the targetTask<TResult> completes. |
ContinueWith(Action<Task<TResult>>, TaskContinuationOptions) | Creates a continuation that executes according the condition specified in |
ContinueWith(Action<Task<TResult>>, TaskScheduler) | Creates a continuation that executes asynchronously when the targetTask<TResult> completes. |
ContinueWith(Action<Task<TResult>>) | Creates a continuation that executes asynchronously when the target task completes. |
ContinueWith(Action<Task>, CancellationToken, TaskContinuationOptions, TaskScheduler) | Creates a continuation that executes when the target task competes according to the specifiedTaskContinuationOptions. The continuation receives a cancellation token and uses a specified scheduler. (Inherited fromTask) |
ContinueWith(Action<Task>, CancellationToken) | Creates a continuation that receives a cancellation token and executes asynchronously when the targetTask completes. (Inherited fromTask) |
ContinueWith(Action<Task>, TaskContinuationOptions) | Creates a continuation that executes when the target task completes according to the specifiedTaskContinuationOptions. (Inherited fromTask) |
ContinueWith(Action<Task>, TaskScheduler) | Creates a continuation that executes asynchronously when the targetTask completes. The continuation uses a specified scheduler. (Inherited fromTask) |
ContinueWith(Action<Task>) | Creates a continuation that executes asynchronously when the targetTask completes. (Inherited fromTask) |
ContinueWith<TNewResult>(Func<Task<TResult>,Object,TNewResult>, Object, CancellationToken, TaskContinuationOptions, TaskScheduler) | Creates a continuation that executes when the targetTask<TResult> completes. |
ContinueWith<TNewResult>(Func<Task<TResult>,Object,TNewResult>, Object, CancellationToken) | Creates a continuation that executes when the targetTask<TResult> completes. |
ContinueWith<TNewResult>(Func<Task<TResult>,Object,TNewResult>, Object, TaskContinuationOptions) | Creates a continuation that executes when the targetTask<TResult> completes. |
ContinueWith<TNewResult>(Func<Task<TResult>,Object,TNewResult>, Object, TaskScheduler) | Creates a continuation that executes when the targetTask<TResult> completes. |
ContinueWith<TNewResult>(Func<Task<TResult>,Object,TNewResult>, Object) | Creates a continuation that executes when the targetTask<TResult> completes. |
ContinueWith<TNewResult>(Func<Task<TResult>,TNewResult>, CancellationToken, TaskContinuationOptions, TaskScheduler) | Creates a continuation that executes according the condition specified in |
ContinueWith<TNewResult>(Func<Task<TResult>,TNewResult>, CancellationToken) | Creates a continuation that executes asynchronously when the targetTask<TResult> completes. |
ContinueWith<TNewResult>(Func<Task<TResult>,TNewResult>, TaskContinuationOptions) | Creates a continuation that executes according the condition specified in |
ContinueWith<TNewResult>(Func<Task<TResult>,TNewResult>, TaskScheduler) | Creates a continuation that executes asynchronously when the targetTask<TResult> completes. |
ContinueWith<TNewResult>(Func<Task<TResult>,TNewResult>) | Creates a continuation that executes asynchronously when the targetTask<TResult> completes. |
ContinueWith<TResult>(Func<Task,Object,TResult>, Object, CancellationToken, TaskContinuationOptions, TaskScheduler) | Creates a continuation that executes based on the specified task continuation options when the targetTask completes and returns a value. The continuation receives caller-supplied state information and a cancellation token and uses the specified scheduler. (Inherited fromTask) |
ContinueWith<TResult>(Func<Task,Object,TResult>, Object, CancellationToken) | Creates a continuation that executes asynchronously when the targetTask completes and returns a value. The continuation receives caller-supplied state information and a cancellation token. (Inherited fromTask) |
ContinueWith<TResult>(Func<Task,Object,TResult>, Object, TaskContinuationOptions) | Creates a continuation that executes based on the specified task continuation options when the targetTask completes. The continuation receives caller-supplied state information. (Inherited fromTask) |
ContinueWith<TResult>(Func<Task,Object,TResult>, Object, TaskScheduler) | Creates a continuation that executes asynchronously when the targetTask completes. The continuation receives caller-supplied state information and uses a specified scheduler. (Inherited fromTask) |
ContinueWith<TResult>(Func<Task,Object,TResult>, Object) | Creates a continuation that receives caller-supplied state information and executes asynchronously when the targetTask completes and returns a value. (Inherited fromTask) |
ContinueWith<TResult>(Func<Task,TResult>, CancellationToken, TaskContinuationOptions, TaskScheduler) | Creates a continuation that executes according to the specified continuation options and returns a value. The continuation is passed a cancellation token and uses a specified scheduler. (Inherited fromTask) |
ContinueWith<TResult>(Func<Task,TResult>, CancellationToken) | Creates a continuation that executes asynchronously when the targetTask completes and returns a value. The continuation receives a cancellation token. (Inherited fromTask) |
ContinueWith<TResult>(Func<Task,TResult>, TaskContinuationOptions) | Creates a continuation that executes according to the specified continuation options and returns a value. (Inherited fromTask) |
ContinueWith<TResult>(Func<Task,TResult>, TaskScheduler) | Creates a continuation that executes asynchronously when the targetTask completes and returns a value. The continuation uses a specified scheduler. (Inherited fromTask) |
ContinueWith<TResult>(Func<Task,TResult>) | Creates a continuation that executes asynchronously when the targetTask<TResult> completes and returns a value. (Inherited fromTask) |
Dispose() | Releases all resources used by the current instance of theTask class. (Inherited fromTask) |
Dispose(Boolean) | Disposes theTask, releasing all of its unmanaged resources. (Inherited fromTask) |
Equals(Object) | Determines whether the specified object is equal to the current object. (Inherited fromObject) |
GetAwaiter() | Gets an awaiter used to await thisTask<TResult>. |
GetHashCode() | Serves as the default hash function. (Inherited fromObject) |
GetType() | Gets theType of the current instance. (Inherited fromObject) |
MemberwiseClone() | Creates a shallow copy of the currentObject. (Inherited fromObject) |
RunSynchronously() | Runs theTask synchronously on the currentTaskScheduler. (Inherited fromTask) |
RunSynchronously(TaskScheduler) | Runs theTask synchronously on theTaskScheduler provided. (Inherited fromTask) |
Start() | Starts theTask, scheduling it for execution to the currentTaskScheduler. (Inherited fromTask) |
Start(TaskScheduler) | Starts theTask, scheduling it for execution to the specifiedTaskScheduler. (Inherited fromTask) |
ToString() | Returns a string that represents the current object. (Inherited fromObject) |
Wait() | Waits for theTask to complete execution. (Inherited fromTask) |
Wait(CancellationToken) | Waits for theTask to complete execution. The wait terminates if a cancellation token is canceled before the task completes. (Inherited fromTask) |
Wait(Int32, CancellationToken) | Waits for theTask to complete execution. The wait terminates if a timeout interval elapses or a cancellation token is canceled before the task completes. (Inherited fromTask) |
Wait(Int32) | Waits for theTask to complete execution within a specified number of milliseconds. (Inherited fromTask) |
Wait(TimeSpan, CancellationToken) | Waits for theTask to complete execution. (Inherited fromTask) |
Wait(TimeSpan) | Waits for theTask to complete execution within a specified time interval. (Inherited fromTask) |
WaitAsync(CancellationToken) | Gets aTask<TResult> that will complete when thisTask<TResult> completes or when the specifiedCancellationToken has cancellation requested. |
WaitAsync(TimeSpan, CancellationToken) | Gets aTask<TResult> that will complete when thisTask<TResult> completes, when the specified timeout expires, or when the specifiedCancellationToken has cancellation requested. |
WaitAsync(TimeSpan, TimeProvider, CancellationToken) | Gets aTask<TResult> that will complete when thisTask<TResult> completes, when the specified timeout expires, or when the specifiedCancellationToken has cancellation requested. |
WaitAsync(TimeSpan, TimeProvider) | Gets aTask<TResult> that will complete when thisTask<TResult> completes or when the specified timeout expires. |
WaitAsync(TimeSpan) | Gets aTask<TResult> that will complete when thisTask<TResult> completes or when the specified timeout expires. |
IAsyncResult.AsyncWaitHandle | Gets aWaitHandle that can be used to wait for the task to complete. (Inherited fromTask) |
IAsyncResult.CompletedSynchronously | Gets an indication of whether the operation completed synchronously. (Inherited fromTask) |
DispatcherOperationWait(Task, TimeSpan) | Waits for the specified amount of time for the underlyingDispatcherOperation to complete. |
DispatcherOperationWait(Task) | Waits indefinitely for the underlyingDispatcherOperation to complete. |
IsDispatcherOperationTask(Task) | Returns a value that indicates whether thisTask is associated with aDispatcherOperation. |
AsAsyncAction(Task) | Returns a Windows Runtime asynchronous action that represents a started task. |
AsAsyncOperation<TResult>(Task<TResult>) | Returns a Windows Runtime asynchronous operation that represents a started task that returns a result. |
All members ofTask<TResult>, except forDispose(), are thread-safe and may be used from multiple threads concurrently.
Was this page helpful?
Was this page helpful?