Task in .NetCore


Parallel programming in .NET Core allows you to execute multiple tasks or operations simultaneously, utilizing multi-core processors to maximize performance and efficiency. The Task Parallel Library (TPL) is the core of parallel programming in .NET Core and provides tools for both data parallelism and task parallelism.

Parallel Task Library (PTL)

The Parallel Task Library (PTL) in .NET Core is a part of the Task Parallel Library (TPL), which provides a set of APIs for running tasks in parallel and managing asynchronous operations. It is widely used in .NET Core Web APIs to enhance performance by executing tasks concurrently.

Key Concepts of PTL in .NET Core

  1. Tasks

    • Represents a unit of work that can be executed asynchronously or in parallel.
    • Created using the Task class or async/await keywords.
  2. Parallelism

    • Executing multiple tasks simultaneously to utilize multi-core processors effectively.
  3. Concurrency

    • Running multiple tasks without necessarily being parallel (tasks may switch contexts).
  4. Data Parallelism

    • Splitting data across multiple tasks for concurrent processing.
  5. Task Coordination

    • Methods like Task.WhenAll, Task.WhenAny, and Task.WaitAll are used to synchronize tasks.

Example 1: Running Multiple Tasks Concurrently

In a Web API, you can execute multiple asynchronous operations in parallel. For example, fetching data from multiple sources.

[ApiController]
[Route("api/[controller]")]
public class DataController : ControllerBase
{
    private readonly IDataService _dataService;

    public DataController(IDataService dataService)
    {
        _dataService = dataService;
    }

    [HttpGet("parallel-data")]
    public async Task<IActionResult> GetParallelData()
    {
        var task1 = _dataService.GetDataFromSource1Async();
        var task2 = _dataService.GetDataFromSource2Async();
        var task3 = _dataService.GetDataFromSource3Async();

        // Execute all tasks in parallel and wait for all to complete
        await Task.WhenAll(task1, task2, task3);

        var result = new
        {
            Source1 = task1.Result,
            Source2 = task2.Result,
            Source3 = task3.Result
        };

        return Ok(result);
    }
}

public interface IDataService
{
    Task<string> GetDataFromSource1Async();
    Task<string> GetDataFromSource2Async();
    Task<string> GetDataFromSource3Async();
}

public class DataService : IDataService
{
    public async Task<string> GetDataFromSource1Async()
    {
        await Task.Delay(1000); // Simulate delay
        return "Data from Source 1";
    }

    public async Task<string> GetDataFromSource2Async()
    {
        await Task.Delay(2000); // Simulate delay
        return "Data from Source 2";
    }

    public async Task<string> GetDataFromSource3Async()
    {
        await Task.Delay(1500); // Simulate delay
        return "Data from Source 3";
    }
}

Example 2: Parallel Processing of a Collection

If you have a collection of items to process, you can use Parallel.ForEach

[HttpPost("process-items")]
public IActionResult ProcessItems([FromBody] List<int> items)
{
    Parallel.ForEach(items, item =>
    {
        // Process each item in parallel
        ProcessItem(item);
    });

    return Ok("Processing completed.");
}

private void ProcessItem(int item)
{
    // Simulate some work
    Thread.Sleep(500);
    Console.WriteLine($"Processed item {item}");
}

Note - Avoid using Parallel.ForEach in Web APIs for tasks involving async/await. Instead, use asynchronous processing with Task.WhenAll.


Prev Next

Top Articles

  1. What is JSON
  2. How to convert a javaScript object in JSON object
  3. Some Important JSON Examples
  4. Common JSON Interview Question