🟢 1️⃣ What is Concurrency?
Concurrency means doing multiple things at the same time, or overlapping tasks in your program.
-
In C#, this usually means using multiple threads or tasks.
-
Goal: make your program faster, or responsive (like not freezing UI).
Example:
-
Downloading 5 files at once instead of waiting for one file to finish before starting the next.
🟢 2️⃣ Ways to Achieve Concurrency in .NET Core
1. Task Parallel Library (TPL)
-
Use the
Task
class to run work asynchronously. -
Example:
✅ Task.Run()
runs work on a thread pool thread.
2. Async / Await
-
For IO-bound tasks (like reading files, HTTP calls), use
async
andawait
. -
Example:
-
async/await
does not block the thread, so the program can do other work while waiting.
3. Parallel Loops
-
Use
Parallel.For
orParallel.ForEach
to run loop iterations concurrently.
-
Automatically splits work across available CPU cores.
4. Concurrent Collections
-
When multiple threads access a collection, use thread-safe collections like:
-
Other options:
ConcurrentQueue
,ConcurrentStack
,ConcurrentDictionary
.
5. Locks (Optional)
-
If you need to protect a resource, use
lock
:
-
Only one thread can access the block at a time.
🟢 3️⃣ Key Tips
-
CPU-bound work →
Task.Run
,Parallel.For
-
IO-bound work →
async/await
-
Shared data → use
Concurrent
collections orlock
-
Avoid blocking threads unnecessarily; async is usually better than
Thread.Sleep
.
🟢 4️⃣ Quick Summary Table
Type | When to Use | Example |
---|---|---|
Task / TPL | CPU-bound or simple background | Task.Run(() => DoWork()) |
Async / Await | IO-bound (file, API, DB) | await HttpClient.GetStringAsync(url) |
Parallel.For | Loop with independent iterations | Parallel.For(0, 10, i => ...) |
ConcurrentCollection | Multiple threads accessing data | ConcurrentBag<int> |
Lock | Protect shared resources | lock(obj) { ... } |
💡 Rule of Thumb:
-
Use async/await for non-CPU tasks.
-
Use Task / Parallel for CPU-heavy tasks.
-
Use concurrent collections to safely share data
No comments:
Post a Comment