Task<TResult> Class
Definition
Represents an asynchronous operation that can return a value.
public class Task<TResult> : System.Threading.Tasks.Task
- TResult
The type of the result produced by this Task<TResult>.
- Inheritance
Inherited Members
System.Object
System.Threading.Tasks.Task
Remarks
The Task<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 the task-based asynchronous pattern first introduced in the .NET Framework 4. Because the work performed by a Task<TResult> object typically executes asynchronously on a thread pool thread rather than synchronously on the main application thread, you can use the Status property, as well as the IsCanceled, IsCompleted, and IsFaulted 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 the .NET Framework 4.5, is to call the static Task.Run<TResult>(Func<TResult>) or Task.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 the Task.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.Tasks
Module 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 Sub
End 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 the .NET Framework 4, is to call the static TaskFactory.StartNew or TaskFactory<TResult>.StartNew method. The Task.Factory property returns a TaskFactory object, and the Task<TResult>.Factory property returns a TaskFactory<TResult> object. Overloads of their StartNew method let you pass arguments, define task creation options, and specify a task scheduler. The following example uses the TaskFactory<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.Tasks
Module 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 Sub
End Module
' The example displays output like the following:
' Finished 1,000,001 iterations
For more complete examples, see Task-based Asynchronous Programming.
The Task<TResult> class also provides constructors that initialize the task but that do not schedule it for execution. For performance reasons, the Task.Run and Task.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's Start method may then be used to schedule the task for execution at a later time.
Starting with desktop apps that target the .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 the .NET Framework prior to the .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 the CultureInfo 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 the Task class. If you're developing with C# 7, for a more lightweight task that is a value type rather than a reference type, use the <xref:System.Threading.Tasks.ValueTask?displayProperty=nameWithType> structure; it is supported starting with C# 7.
Constructors
Properties
| Factory |
Provides access to factory methods for creating and configuring Task<TResult> instances. |
| Result |
Gets the result value of this Task<TResult>. |
Methods
Extension Methods
| Unwrap(Task<Task>) | |
| Unwrap<TResult>(Task<Task<TResult>>) | |
| DispatcherOperationWait(Task) | |
| DispatcherOperationWait(Task, TimeSpan) | |
| IsDispatcherOperationTask(Task) |
Thread Safety
All members of Task<TResult>, except for Dispose(), are thread-safe and may be used from multiple threads concurrently.