The Task class, introduced in .NET Framework 4.0 under the System.Threading.Tasks namespace, is part of the Task Parallel Library (TPL). It provides a high-level abstraction for asynchronous and parallel programming, enabling background execution without blocking the main thread.
It simplifies thread management, integrates with async/await and supports cancellation and exception handling for efficient multithreading.
Key Features of the Task Class
- Supports cooperative cancellation using CancellationToken.
- Reduces the need for manual synchronization primitives like Mutex or Monitor.
- Uses the Thread Pool, ensuring efficient handling of CPU-bound and I/O-bound operations.
- Aggregates exceptions using AggregateException for structured error handling.
- Integrates with async/await, supports continuations and manages background threads automatically.
Declaration
public class Task : IAsyncResult, IDisposable
The Task class implements IAsyncResult (for asynchronous operations) and IDisposable (for resource cleanup).
Example: Creating and Running a Task
using System;
using System.Threading.Tasks;
class Geeks
{
static void Main()
{
int num1 = 3, num2 = 5, num3 = 7;
// Creating a Task using Func<TResult> delegate
Task<int> task = new Task<int>(() => Multiply(num1, num2, num3));
task.Start(); // Start execution
task.Wait(); // Wait for completion
Console.WriteLine($"Task result: {task.Result}");
}
static int Multiply(int a, int b, int c)
{
return a * b * c;
}
}
Output
Task result: 105
Explanation: Here, the Task<int> is created with a Func<int> delegate that calls the Multiply method asynchronously. The task is started using Start() and awaited using Wait(). After completion, the result is retrieved via task.Result.
Constructors
- Task(Action action): Initializes a task with the specified action.
- Task(Action action, CancellationToken cancellationToken): Initializes a task with an action and a cancellation token.
- Task(Action action, TaskCreationOptions creationOptions): Allows configuring scheduling behavior using TaskCreationOptions.
- Task(Action action, CancellationToken cancellationToken, TaskCreationOptions creationOptions): Creates a task with full control over action, cancellation and scheduling.
- Task(Action<object?> action, object? state): Passes a state object to the action when the task executes.
- Task(Action<object?> action, object? state, CancellationToken cancellationToken): Creates a task with a state object and a cancellation token.
- Task(Action<object?> action, object? state, TaskCreationOptions creationOptions): Creates a task with state and custom creation options.
- Task(Action<object?> action, object? state, CancellationToken cancellationToken, TaskCreationOptions creationOptions): Provides complete customization over task creation and execution behavior.
Example: Task Cancellation using CancellationToken
using System;
using System.Threading;
using System.Threading.Tasks;
class Geeks
{
static void Main()
{
CancellationTokenSource cts = new CancellationTokenSource();
Task task = new Task(() =>
{
for (int i = 0; i < 3; i++)
{
if (cts.Token.IsCancellationRequested)
{
Console.WriteLine("Task canceled!");
return;
}
Console.WriteLine($"Task is working... {i}");
Thread.Sleep(100);
}
}, cts.Token);
task.Start();
Thread.Sleep(300); // Simulate condition
cts.Cancel(); // Request cancellation
task.Wait();
}
}
Output
Task is working... 0 Task is working... 1 Task is working... 2
Explanation: The task runs asynchronously and checks the CancellationToken. When cts.Cancel() is called, the task acknowledges the cancellation request and stops execution safely.
Commonly Used Methods
- ConfigureAwait(Boolean): Configures whether the continuation should run on the same thread.
- ContinueWith(Action): Runs a specified action when the task completes.
- ContinueWith(Func<Task, TResult>): Runs a continuation that returns a result.
- Delay(Int32): Creates a task that completes after a specified delay in milliseconds.
- Dispose(): Releases resources used by the task.
- FromCanceled(CancellationToken): Creates a task that is already canceled.
- FromException(Exception): Creates a task completed with an exception.
- FromResult(TResult): Creates a task completed successfully with the specified result.
- GetAwaiter(): Returns an awaiter for asynchronous waiting.
- Run(Action): Runs an action asynchronously and returns a task.
- Run(Func<TResult>): Runs a function asynchronously and returns a task that produces a result.
- RunSynchronously(): Executes the task on the current thread synchronously.
- Start(): Starts the execution of the task.
- Wait(): Blocks the current thread until the task completes.
- Wait(Int32): Waits for a task to complete within a specific timeout.
- WaitAll(Task[]): Waits for all provided tasks to complete.
Example: Continuation and Synchronous Execution
using System;
using System.Threading;
using System.Threading.Tasks;
class Geeks
{
static void Main()
{
CancellationTokenSource cts = new CancellationTokenSource();
Task task = new Task(() =>
{
for (int i = 0; i < 3; i++)
{
if (cts.Token.IsCancellationRequested)
{
Console.WriteLine("Task was canceled!");
return;
}
Console.WriteLine($"Task is working... {i}");
Thread.Sleep(100);
}
}, cts.Token);
task.Start();
Task continuation = task.ContinueWith(t =>
{
if (t.IsCanceled)
Console.WriteLine("Continuation: Task was canceled.");
else
Console.WriteLine("Continuation: Task completed.");
});
Thread.Sleep(300);
cts.Cancel();
try
{
task.Wait();
}
catch (AggregateException ex)
{
if (ex.InnerExceptions[0] is TaskCanceledException)
Console.WriteLine("Caught TaskCanceledException.");
}
continuation.Wait();
Task syncTask = new Task(() => Console.WriteLine("Running task synchronously."));
syncTask.RunSynchronously();
Console.WriteLine("Main thread is not blocked.");
}
}
Output
Task is working... 0 Task is working... 1 Task is working... 2 Continuation: Task completed. Running task synchronously. Main thread is not blocked.
Explanation: ContinueWith() executes a continuation after the original task finishes. RunSynchronously() runs a task on the current thread without scheduling it in the thread pool.
Commonly Used Properties
- Id: Returns the unique ID of the task.
- CurrentId: Gets the ID of the currently executing task.
- Exception: Returns the AggregateException that caused premature termination.
- Status: Returns the current status of the task.
- IsCanceled: Indicates whether the task was canceled.
- IsCompleted: Indicates whether the task has completed execution.
- IsCompletedSuccessfully: Indicates successful completion without errors or cancellations.
- CancellationToken: Returns the CancellationToken associated with the task.
- AsyncState: Gets the user-defined state object supplied when the task was created.
- Factory: Returns the default TaskFactory instance used to create tasks.
- CreationOptions: Returns the TaskCreationOptions used for this task.
- CompletedTask: Returns a task that is already successfully completed.
Example: Accessing Task Properties
using System;
using System.Threading;
using System.Threading.Tasks;
class Geeks
{
static void Main()
{
CancellationTokenSource cts = new CancellationTokenSource();
Task task = new Task(() =>
{
for (int i = 0; i < 3; i++)
{
if (cts.Token.IsCancellationRequested)
{
Console.WriteLine("Task was canceled!");
return;
}
Console.WriteLine($"Task is working... {i}");
Thread.Sleep(100);
}
}, cts.Token);
task.Start();
Console.WriteLine($"Task ID: {task.Id}");
Console.WriteLine($"Task Status: {task.Status}");
Console.WriteLine($"Task IsCompleted: {task.IsCompleted}");
Thread.Sleep(300);
cts.Cancel();
try
{
task.Wait();
}
catch (AggregateException ex)
{
if (ex.InnerExceptions[0] is TaskCanceledException)
Console.WriteLine("Caught TaskCanceledException.");
}
Console.WriteLine($"Task IsCompleted: {task.IsCompleted}");
}
}
Output
Task ID: 1 Task is working... 0 Task Status: Running Task IsCompleted: False Task is working... 1 Task is working... 2 Task IsCompleted: True
Explanation: The Id property uniquely identifies a task, Status shows its execution state and IsCompleted reflects whether the task has finished execution.