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.
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.
Tasks
Parallelism
Concurrency
Data Parallelism
Task Coordination
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";
}
}
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.