问题
I am working with async-await and tasks, but I can't understand the one thing:
Is async task executes in separate thread?
As msdn says (Asynchronous programming):
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.
But in the remarks in description of ThreadPool class (ThreadPool Class):
Examples of operations that use thread pool threads include the following:
When you create a Task or Task object to perform some task asynchronously, by default the task is scheduled to run on a thread pool thread.
So, now I don't understand if async task uses separate thread. Explain me please. Thanks.
回答1:
A Task does not necessarily represent an extra thread.
If you await a Task, you return the control flow to the caller of your method until "someone" sets the Task as completed.
If you start a Task via Task.Run() or Task.Factory.StartNew(), then the action you pass to these calls is executed on another thread (not a new one, but one from the ThreadPool).
回答2:
async/await work on Tasks (well not exactly, it works on "awaitables", but just saying "Task" is close enough for this discussion).
Tasks represent "A unit of work that will be completed at a later time". That unit of work could be a new thread from the thread pool started via Task.Run(, it could be a system IO call like DbDataReader.ReadAsync(), or it could be triggered by a event from a TaskCompletionSource.
I recommend reading Stephen Cleary's async and await intro to learn more about the
回答3:
To put it in a simple term Task can run on a different Thread as well as it can run on the caller Thread. Task will take a Thread from a ThreadPool ONLY when caller Thread does not have resources to run another Task. Task will be ran on caller Thread when it has enough resources to run another Task (idle mode).
Compared to a thread, a Task is a higher-level abstraction—it represents a concurrent operation that may or may not be backed by a thread. Tasks are compositional (you can chain them together through the use of continuations). They can use the thread pool to lessen startup latency, and with a TaskCompletionSource, they can leverage a callback approach that avoid threads altogether while waiting on I/O-bound operations.
Source: page 565 "C# 5.0 in a Nutshell" by Joseph Albahari, Ben Albahari.
来源:https://stackoverflow.com/questions/37278281/async-await-and-threads