TaskClass
Represents an asynchronous operation.
Summary
Fields
Properties
Methods
Constructors
Static Fields
CompletedTask
Gets a task that has already completed.
Constructors
Task(Action action)
Initializes a new instance of the Task class with the specified delegate.
Task(Action action, TaskCreationOptions creationOptions)
Initializes a new instance of the Task class with the specified delegate and task creation options.
Task(Func<TResult> function)
Initializes a new instance of the Task<TResult> class with the specified delegate.
Task(Func<TResult> function, TaskCreationOptions creationOptions)
Initializes a new instance of the Task<TResult> class with the specified delegate and task creation options.
Instance Properties
AsyncState
Gets the state variable for the asynchronous operation.
CreationOptions
Gets the delegate used to create the task.
Id
Gets a unique identifier for this Task instance.
IsCanceled
Gets whether the task has been canceled.
IsCompleted
Gets whether the task has completed.
IsCompletedSuccessfully
Gets whether the task has completed successfully.
IsFaulted
Gets whether the task has finished with an exception.
Method
Gets the delegate used to create the task.
Result
Gets the result of the task. (For Task<TResult>)
Status
Gets the status of the task.
Instance Methods
Dispose()
Releases the resources used by the current instance of the Task class.
GetAwaiter()
Returns an awaiter for this task.
Wait()
Blocks the calling thread until the task completes.
Wait(int millisecondsTimeout)
Blocks the calling thread until the task completes or the specified time elapses.
ContinueWith(Action<Task> continuationAction)
Schedules the continuation to run after the task completes.
ContinueWith<TResult>(Func<Task, TResult> continuationFunction)
Schedules the continuation to run after the task completes and returns its result.
Static Methods
Task.Run(Action action)
Enqueues a {@link Action} for execution and returns a task that represents the execution of that action.
Example
// Run a simple asynchronous operation
Task.Run(() => {
Console.WriteLine("Performing a background task...");
Thread.Sleep(1000);
Console.WriteLine("Background task finished.");
});
// Run an asynchronous operation that returns a value
Task sumTask = Task.Run(() => {
return 10 + 20;
});
int result = sumTask.Result; // This will block until the task is complete
Console.WriteLine($"The sum is: {result}");
Task.Delay(int millisecondsDelay)
Creates a task that will complete after a specified number of milliseconds.
Example
async Task PerformDelayedOperation() {
Console.WriteLine("Waiting for 2 seconds...");
await Task.Delay(2000);
Console.WriteLine("2 seconds have passed!");
}
Task.WhenAll(params Task[] tasks)
Creates a task that will complete when all of the supplied tasks have completed.
Example
Task task1 = Task.Run(() => { Console.WriteLine("Task 1"); Thread.Sleep(500); });
Task task2 = Task.Run(() => { Console.WriteLine("Task 2"); Thread.Sleep(700); });
await Task.WhenAll(task1, task2);
Console.WriteLine("All tasks completed.");
Task.WhenAny(params Task[] tasks)
Creates a task that will complete when any of the supplied tasks have completed.
Example
Task task1 = Task.Run(async () => { await Task.Delay(1000); Console.WriteLine("Task 1 done"); });
Task task2 = Task.Run(async () => { await Task.Delay(500); Console.WriteLine("Task 2 done"); });
Task completedTask = await Task.WhenAny(task1, task2);
Console.WriteLine($"The first task to complete was: {completedTask.Id}");
Remarks
The
Task
class represents an asynchronous operation that does not return a value.
For asynchronous operations that return a value, use the generic Task<TResult>
class.
Tasks are the fundamental building blocks of asynchronous programming in .NET,
enabling responsive user interfaces and efficient server applications.
They provide a clean way to manage concurrency, handle exceptions, and compose asynchronous operations.
Example
Basic Usage
using System;
using System.Threading;
using System.Threading.Tasks;
public class Example {
public static void Main(string[] args) {
Console.WriteLine("Starting the main thread.");
// Create and start a new task
Task myTask = Task.Run(() => {
Console.WriteLine("Task is running on thread: " + Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(2000); // Simulate work
Console.WriteLine("Task finished.");
});
Console.WriteLine("Main thread continues while task is running.");
// Wait for the task to complete
myTask.Wait();
Console.WriteLine("Task has completed. Main thread exiting.");
}
}