问题描述
我不明白的东西有关异步/的await:
I don´t understand something about async/await:
这是强制性的,异步方法必须有一个内部电话的await ......但如果有一个等待着它,因为它是调用另一个异步方法,对不对?因此,它似乎是内部调用另一个异步方法与等待着异步方法循环链。
It is mandatory that an async method must have an await call inside... But if there is an await it is because it is calling another async method, right? So it seems to be an endless chain of async methods with awaits inside calling another async methods.
所以是有可能创造一个第一异步方法,不是要求内部的任何其他异步方法。只要创建一个异步方法,因为这种方法做了很多可能会拖慢系统的工作。
So is it possible to create a "first" async method, not calling any other async methods inside. Just create an async method because that method does a lot of work that could slow down the system.
推荐答案
一个方法并不需要的await为异步
,它周围的其他方式。您只能在一个异步
方法中使用等待
。您的可以的有一个返回工作
没有它被标记为异步
的方法。更多。
First, some clarifications
A method doesn't need an await to be async
, it's the other way around. You can only use await
in an async
method. You may have a method that returns a Task
without it being marked as async
. More here.
IIUC,大约是的根所有异步的。
所以,是的,它的是的可能创造一个第一异步
方法。它只是一个返回工作
(或任务< T>
)的方法。
IIUC, is about "The Root Of All Async".So, yes, it is possible to create a "first" async
method. It's simply a method that returns a Task
(or Task<T>
).
有两种类型的这些任务:。
There are two types of these tasks: A Delegate Task and a Promise Task.
- 一个委托的任务是由
Task.Run
燃煤(最次。Task.StartNew
和新建任务(()=&GT; {});
其他选项),它具有code运行。这主要是用于卸载工作。 - 一个承诺任务是
工作
实际上并不执行任何code,它只是一种机制,以 等待到通过的的工作
完成的在得到通知。 湾信令完成的使用的的工作
。这与,并主要用于本质异步操作(也为异步
同步对象)例如:
- A Delegate Task is fired by
Task.Run
(most times.Task.StartNew
andnew Task(() => {});
are other options) and it has code to run. This is mostly used for offloading work. - A Promise Task is a
Task
that doesn't actually execute any code, it's only a mechanism to a. Wait to be notified upon completion by theTask
. b. Signaling completion using theTask
. This is done withTaskCompletionSource
and is mostly used for inherently asynchronous operations (but also forasync
synchronization objects) for example:
private static Task DoAsync()
{
var tcs = new TaskCompletionSource<int>();
new Thread(() =>
{
Thread.Sleep(1000);
tcs.SetResult(5);
}).Start();
return tcs.Task;
}
这些工具允许您创建的根,但除非你实施 I / O
库(如净
的 DNS
类)或同步对象(如的)你自己,你很少会使用它们。
These tools allow you to create those "roots", but unless you implement an I/O
library (like .Net
's DNS
class) or a synchronization object (like SemaphoreSlim
) yourself, you would rarely use them.
这篇关于无尽的异步和等待?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!