无尽的异步和等待? [英] Endless async and await?

查看:91
本文介绍了无尽的异步和等待?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白的东西有关异步/的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.


  1. 一个委托的任务是由 Task.Run 燃煤(最次。 Task.StartNew 新建任务(()=&GT; {}); 其他选项),它具有code运行。这主要是用于卸载工作。

  2. 一个承诺任务是工作实际上并不执行任何code,它只是一种机制,以 等待到通过的的工作完成的在得到通知。 信令完成的使用的的工作。这与 TaskCompletionSource完成 ,并主要用于本质异步操作(也为<一个href=\"http://blogs.msdn.com/b/pfxteam/archive/2012/02/12/building-async-coordination-primitives-part-7-asyncreaderwriterlock.aspx\"相对=nofollow> 异步同步对象)例如:

  1. A Delegate Task is fired by Task.Run (most times. Task.StartNew and new Task(() => {}); are other options) and it has code to run. This is mostly used for offloading work.
  2. 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 the Task. b. Signaling completion using the Task. This is done with TaskCompletionSource and is mostly used for inherently asynchronous operations (but also for async 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 类)或同步对象(如的 SemaphoreSlim )你自己,你很少会使用它们。

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.

这篇关于无尽的异步和等待?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆