Async await and threads [duplicate]

荒凉一梦 提交于 2019-11-30 20:48:12

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).

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!