Monday, 22 September 2025

Parallel Library (TPL)

1️⃣ What Is the Task Parallel Library (TPL)?

  • TPL is part of the System.Threading.Tasks namespace.

  • It helps you run code in parallel (many things at the same time) or asynchronously (not blocking the main thread).

  • It manages threads for you, so you don’t need to manually create or destroy them.


2️⃣ Key Concepts

Task

  • Represents a unit of work that runs on a separate thread pool thread.

  • Similar to “a promise to finish some work.”

Example:

using System; using System.Threading.Tasks; class Program { static async Task Main() { Task t = Task.Run(() => { Console.WriteLine("Hello from a background task!"); }); await t; // waits until t is finished Console.WriteLine("Task completed."); } }

3️⃣ Starting Tasks

You can start tasks in different ways:

Task task1 = Task.Run(() => DoWork()); Task task2 = new Task(DoWork); task2.Start();

Task.Run is simpler and recommended.


4️⃣ Returning Values

Tasks can return results using Task<T>:

Task<int> t = Task.Run(() => { return 5 + 3; }); int result = await t; Console.WriteLine(result); // 8

5️⃣ Waiting for Many Tasks

You can wait for multiple tasks:

  • All tasks must finish:

await Task.WhenAll(task1, task2, task3);
  • Any one finishes first:

await Task.WhenAny(task1, task2);

6️⃣ Parallel Loops

TPL provides helpers to run loops in parallel:

Parallel.For

Parallel.For(0, 10, i => { Console.WriteLine($"Processing item {i}"); });

Parallel.ForEach

string[] names = { "A", "B", "C" }; Parallel.ForEach(names, name => { Console.WriteLine(name); });

These automatically split work across available CPU cores.


7️⃣ Handling Exceptions

Use try/catch around await:

try { await Task.Run(() => throw new Exception("Oops")); } catch (Exception ex) { Console.WriteLine(ex.Message); }

8️⃣ Cancellation

Use CancellationToken to stop tasks early.

var cts = new CancellationTokenSource(); Task t = Task.Run(() => { for (int i = 0; i < 10; i++) { cts.Token.ThrowIfCancellationRequested(); Console.WriteLine(i); Task.Delay(500).Wait(); } }, cts.Token); // Cancel after 1 second cts.CancelAfter(1000);

9️⃣ Best Practices

  • Prefer await over Task.Wait() to avoid blocking.

  • Avoid creating too many tasks at once; let TPL handle scheduling.

  • Use async/await for clean, readable code.


Quick Summary

FeatureExampleUse When
Task.Runawait Task.Run(Work);Run work in background
Task<T>var r = await Task.Run(() => 5 + 3);Need a result from the task
Parallel.For/ForEachParallel.For(0, n, i => Work(i));Process many items in parallel
Task.WhenAllawait Task.WhenAll(t1, t2);Wait for multiple tasks
CancellationTokencts.Cancel();Gracefully stop a task if needed

With these basics, you can start writing parallel or asynchronous code in .NET Core using TPL safely and effectively.

You said:
more simple and details way
ChatGPT said:

Sure! Let’s break the Task Parallel Library (TPL) into very simple words and add more step-by-step details.


🟢 1. What is TPL?

  • Full name: Task Parallel Library

  • Purpose: Run many pieces of code at the same time or without blocking your main program.

  • Think of it as asking helpers to finish small jobs while you keep working.

Without TPL: you write code → wait → write next code.
With TPL: you write code → ask helpers to do work → you keep going.


🟢 2. Important Word: Task

  • A Task is just “a job” for the computer.

  • You tell .NET: “Please run this job in the background.”


🟢 3. How to Make a Task

Example 1: Start a task

using System; using System.Threading.Tasks; class Program { static async Task Main() { Task t = Task.Run(() => { Console.WriteLine("Job running in background"); }); await t; // Wait until the job finishes Console.WriteLine("Job done"); } }

Explanation:

  • Task.Run starts the job.

  • await t waits until it is done.


🟢 4. Task that Returns a Value

You can get a result back, like a calculator.

Task<int> t = Task.Run(() => { return 5 + 3; }); int answer = await t; Console.WriteLine(answer); // prints 8

Here Task<int> means the job will give back an int number.


🟢 5. Run Many Tasks Together

You can start many jobs and wait for all to finish.

Task t1 = Task.Run(() => Console.WriteLine("Job 1")); Task t2 = Task.Run(() => Console.WriteLine("Job 2")); await Task.WhenAll(t1, t2); // waits for both Console.WriteLine("All jobs done");
  • WhenAll → wait until all are done.

  • WhenAny → wait until the first one finishes.


🟢 6. Parallel Loops

If you want to process many items faster:

Parallel.For(0, 5, i => { Console.WriteLine($"Item {i}"); });
  • It splits the numbers 0–4 across different CPU cores.

For lists:

string[] names = { "A", "B", "C" }; Parallel.ForEach(names, n => { Console.WriteLine(n); });

🟢 7. Cancel a Task

Sometimes you need to stop a running job.

var cts = new CancellationTokenSource(); Task t = Task.Run(() => { for (int i = 0; i < 10; i++) { cts.Token.ThrowIfCancellationRequested(); Console.WriteLine(i); Task.Delay(500).Wait(); } }, cts.Token); // cancel after 1 second cts.CancelAfter(1000);

CancellationTokenSource sends a signal to stop.


🟢 8. Handle Errors

Tasks can throw errors (exceptions). Use try…catch:

try { await Task.Run(() => throw new Exception("Something broke")); } catch (Exception ex) { Console.WriteLine(ex.Message); }

🟢 9. Best Tips

  • Use await (not Task.Wait) so the main thread isn’t blocked.

  • Let TPL manage threads—you rarely need Thread class.

  • Too many tasks at once may slow you down.
    Start only as many as you need.


🟢 10. Quick Cheat Sheet

ActionCode Example
Run simple taskawait Task.Run(() => Work());
Get resultint r = await Task.Run(() => 5+3);
Wait for manyawait Task.WhenAll(t1, t2);
Loop in parallelParallel.For(0, n, i => Work(i));
Stop a taskcts.Cancel();
Handle errorstry { await task; } catch { }

🟢 In One Line:

TPL = “Ask .NET to run jobs in the background, in parallel, and give you the result when ready—without you managing threads.”

With these basics and code snippets, you can safely start using Task Parallel Library in .NET Core with simple C#.

No comments:

Post a Comment