Note: this article is published on 07/08/2024.
This is a series of articles about Multi-threading.
- Multi-Threading (1), Concept: What, Why
- Multi-Threading (2), Implementation Overview
- Multi-Threading (3), async, await in C#
- Multi-Threading (4), delegate based Asynchronous Programming Model
- Multi-Threading (5), Summary --- this article
A - Introduction
We already have several articles to discuss the Async programming. This article will be a summary.
In article, Multi-Threading (2), Implementation Overview, we mentioned there are three Async programming patterns, for .NET:
- Task-based Asynchronous Pattern (TAP).
- Event-based Asynchronous Pattern (EAP).
- Asynchronous Programming Model (APM) pattern (also called the IAsyncResult pattern).
In article, Multi-Threading (2-1), Different MultiThreading Topics, we mentioned .Net has three low-level mechanisms to run Async code in parallel:
Thread,ThreadPool, andTask.
These three mechanism serve different purposes.
In this article, we will first briefly discuss the three async low-level machanisms, and conclude that the task machanism is the best choice for the modern programming. In the second section, we will discuss briefly the ways to make the threading programming, while in the last section, we will briefly describe the major features of the task machanism.
This is a summary of the multi-threading issue, will discuss the topics
- A - Introduction
- B - Task vs. Threading --- the choice of three async machanism
- B1 - Thread
- B2 - ThreadPool
- B3 - Task
- B4 - Conclusion
- C - The ways to implemente Threading --- the traditional way
- C1 - Asynchronous Programming Model Pattern
- C2 - Event-Based Asynchronous Pattern
- C3 - Threading Class
- D - Task and async/await --- The Current Way
- D1 - Task
- D2 - async and asit keywords
- E - Task Exception Handling
- E1
- try/catchstatement - E2 - By Task method: FromException
- E1
B - Threads vs. Tasks --- the choice of three async machanism
.Net has three low-level mechanisms to run code in parallel: Thread, ThreadPool, and Task. These three mechanism serve different purposes.
B1 - Thread
- The thread represents an actual OS-level thread with the highest degree of control; you can
- Abort() or Suspend() or Resume() a thread (though this is a very bad idea),
- Observe its state,
- Set thread-level properties like
- stack size,
- apartment state, or
- culture.
- The problem with Thread is that OS threads are costly. Each thread you have
- Consumes a non-trivial amount of memory for its stack and
- Adds additional CPU overhead as the processor context-switch between threads.
- Developed by Developer from creating to whole manipulating.
B2 - ThreadPool
- ThreadPool is a wrapper around a pool of threads maintained by the CLR. ThreadPool gives you no control at all; you can
- Submit work to execute at some point, and you can
- Control the size of the pool, but you
- Can't set anything else. You can't even tell when the pool will start running the work you submit to it.
- Using ThreadPool avoids the overhead of creating too many threads. However,
- If you submit too many long-running tasks to the threadpool, it can get full, and later work that you submit can end up waiting for the earlier long-running items to finish. In addition,
- The ThreadPool offers no way to find out when a work item has been completed (unlike Thread.Join()),
- Nor a way to get the result. Therefore,
- ThreadPool is best used for short operations where the caller does not need the result.
B3 - Task
- Finally, the Task class from the Task Parallel Library offers the best of both worlds.
- Like the ThreadPool, a task does not create its own OS thread. Task runs on the ThreadPool through a TaskScheduler.
- Unlike the ThreadPool, Task also allows you to find out when it finishes and return a result.
- All newer high-level concurrency APIs, including the Parallel.For*() methods, PLINQ, C# 5 await, and modern async methods in the BCL, are all built on Task.
B4 - Conclusion
- The bottom line is that Task is almost always the best option; it provides a much more powerful API and avoids wasting OS threads.
- The only reasons to explicitly create your own Threads in modern code are setting per-thread options or maintaining a persistent thread that needs to maintain its own identity.
C - The ways to implemente Threading
The major will be like below:
C1 - Asynchronous Programming Model Pattern
- A native or raw asynchronous programming model using a delegate to create a thread. such that you define a delegate with the same signature as the method you want to call, the common language runtime automatically defines
BeginInvokeandEndInvokemethods for this delegate, with the appropriate signatures. Therefore, we could say APM is a delegate-based Asynchronous Programming model.

APM Pattern (ref)
C2 - Event-Based Asynchronous Pattern
-
The Event-based Asynchronous Pattern has a single MethodNameAsync method and a corresponding MethodNameCompleted event
-
Basically, this pattern enforces a pair of methods and an event to collaborate and help the application execute a thread asynchronously

Event-Based Pattern (ref)
C3 - Threading class:
- Create a threading class
Thread t = new Thread(worker);
t.Start(); //start a new thread, call the method WorkerThreadMethod
- Manage Thread lifetime: We use thread class properties to manage thread lifetime:
- Start --- Start a thread
- Sleep(TimeSpan) --- block the thread at a certain time (Static Method, only can be called from within the current thread)
- Join --- Blocks the calling thread until the called thread terminates
- Suspend/ Resume --- Suspend/Resume the thread
- Interrupt --- Interrupts a thread that is in the WaitSleepJoin thread state
- Abort --- terminate the thread, throwing a ThreadAobrtException
D - Task and async/await
This section will discuss the major features of the task machanism.
D1 - Task
The Task Parallel Library (TPL) is based on the concept of a task, which represents an asynchronous operation. In some ways, a task resembles a thread or ThreadPool work item but at a higher level of abstraction. The term task parallelism refers to one or more independent tasks running concurrently. Tasks provide two primary benefits:
-
More efficient and more scalable use of system resources.
Behind the scenes, tasks are queued to the ThreadPool, which has been enhanced with algorithms that determine and adjust to the number of threads. These algorithms provide load balancing to maximize throughput. This process makes tasks relatively lightweight, and you can create many of them to enable fine-grained parallelism.
-
More programmatic control than is possible with a thread or work item.
Tasks and the framework built around them provide a rich set of APIs that support waiting, cancellation, continuations, robust exception handling, detailed status, custom scheduling, and more.











Join the conversation! Your thoughts help the community grow.