0. What is multi threads?
Sometimes a problem can be divided into multiple pieces to compute separately, this is called parallel programming, and we can use multiple threads to achieve it.
It makes use of CPU cores or available threads to achieve better performance.
Without multithreads we have to run them sequentially, thus taking more time.
- async programming (allows a way to run a continuation as the operation completes, doesn’t block current thread)
Concurrency（并发） vs Parallelism（并行）
Concurrency is the task of running and managing the multiple computations at the same time. While parallelism is the task of running multiple computations simultaneously.
Concurrency is two lines of customers ordering from a single cashier (lines take turns ordering); Parallelism is two lines of customers ordering from two cashiers (each line gets its own cashier).
Concurrency 就是可以在做了一半 A 任务的时候去执行 B 任务。
Parallelism 就是可以同时执行 A、B 两个任务。
How many core/threads do I have?
On Windows you can open Task Manager and check your CPU specs in the performance tab. 12 cores/threads means 12 concurrent operations.
Note: core and thread are interchangeable terms.
PPS: If your machine only has one core, you won’t benefit from parallelism.
1. Key Points
- Two ways of achieving parallel programming in .NET:
- use lower level thread class (more control, more responsibility, more code, more error-prone)
- use TPL’s abstraction (preferred way, manages threads for us)
- When to use Parallel programming?
- CPU bound operations
- Independent chunks of data
- When to use Async programming?
- I/O operations
- Waiting for other services to return result (e.g., calling APIs)
- Misusing Parallel in ASP.NET can cause bad performance for all users.
- if a user invocation utilizes all the available cores on the server, the other users won’t be able to access the resource.
- server side heavy computation based on invocation should be handled in other ways (architectural level)