Created
December 29, 2019 03:47
-
-
Save wantedfast/38617d4f4f9bd9f25416309a9ba47115 to your computer and use it in GitHub Desktop.
What's the difference between Thread and Task in C#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ## Difference | |
| 1. The Thread class is used for creating and manipulating a thread in Windows. | |
| 2. A Task represents some asynchronous operation and is part of the Task Parallel Library, a set of APIs for running tasks asynchronously and in parallel. | |
| 3. The task can return a result. There is no direct mechanism to return the result from a thread. | |
| 4. Task supports cancellation through the use of cancellation tokens. But Thread doesn't. | |
| 5. A task can have multiple processes happening at the same time. Threads can only have one task running at a time. We can easily implement Asynchronous using ’async’ and ‘await’ keywords. | |
| 6. A new Thread()is not dealing with Thread pool thread, whereas Task does use thread pool thread. | |
| 7. A Task is a higher level concept than Thread. | |
| ## Async Programming | |
| Async methods are intended to be non-blocking operations. An await expression in an async method doesn't block the current thread while the awaited task is running. Instead, the expression signs up the rest of the method as a continuation and returns control to the caller of the async method. | |
| The async and await keywords don't cause additional threads to be created. Async methods don't require multithreading because an async method doesn't run on its own thread. The method runs on the current synchronization context and uses time on the thread only when the method is active. You can use Task.Run to move CPU-bound work to a background thread, but a background thread doesn't help with a process that's just waiting for results to become available. | |
| The async-based approach to asynchronous programming is preferable to existing approaches in almost every case. In particular, this approach is better than the BackgroundWorker class for I/O-bound operations because the code is simpler and you don't have to guard against race conditions. In combination with the Task.Run method, async programming is better than BackgroundWorker for CPU-bound operations because async programming separates the coordination details of running your code from the work that Task.Run transfers to the threadpool. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment