Concurrency

C# Tasks

Using Tasks

C# Tasks enable asynchronous programming with Task.Run.

Introduction to C# Tasks

C# Tasks provide a way to run code asynchronously, allowing for better performance and responsiveness in applications. The Task class in C# represents an asynchronous operation, and is part of the System.Threading.Tasks namespace.

Tasks are particularly useful in scenarios where you need to perform time-consuming operations without blocking the main thread, such as file I/O or network requests.

Creating and Running Tasks

To create and run a task, you can use the Task.Run method. This method queues the specified work to run on the thread pool and returns a task object that represents the asynchronous operation.

Here's a simple example of creating and running a task:

Handling Task Results

Tasks can return results using the Task<TResult> class. This is useful when you need to perform an asynchronous operation that produces a value.

In the following example, we create a task that returns an integer:

Waiting for Tasks to Complete

There are several methods to wait for tasks to complete. The Wait method blocks the calling thread until the task finishes. Alternatively, you can use the await keyword in an async method to wait for the task asynchronously.

Here's an example using the Wait method:

Canceling Tasks

Tasks can be canceled by using a CancellationToken. This allows you to cancel a task in response to a user action or other conditions.

Here's how you can implement task cancellation:

Conclusion

C# Tasks are a powerful feature of the .NET framework that enable asynchronous programming, making applications more responsive and efficient. By using Task.Run and handling task results, waiting for completion, and managing cancellation, developers can build robust and scalable applications.

In the next post of this series, we will explore Async/Await, which builds on the foundation of tasks to simplify asynchronous programming in C#.

Previous
Queues