为什么要使用异步/等待一路下滑 [英] Why use Async/await all the way down

查看:95
本文介绍了为什么要使用异步/等待一路下滑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获得什么是使用等待和异步的一路下跌的好处一些澄清。

I would like to get some clarification on what is the added benefit of using of Await and Async all the way down.

如果我的应用程序在调用的await FUNC1()(所以不堵到UI这里)。和 FUNC1 正在调用的await FUNC2(),但的结果FUNC2()是>为 FUNC1 FUNC2() awaitable。因为它等待 FUNC2 完成 FUNC1()执行会一样长的时间。所有什么的await在这里做的是加入的StateMachine开销。

If my application is calling await Func1() (So no blocking to the UI here). and Func1 is calling await Func2(), but the results from Func2() are important for Func1 to complete it's job, then why would I need to make Func2() awaitable. Func1() execution will take just as long because it's waiting on Func2 to finish. All what the await is doing here is adding the StateMachine overhead.

我失去了一些东西在这里?

Am I missing something here?

推荐答案

一个更好的口号的就是 异步一路攀升。因为你开始一个异步操作,并使其异步调用者再下来电者等。

A better slogan is async all the way up. Because you start with an asynchronous operation and make its caller asynchronous and then the next caller etc.

您应该使用异步等待当你有一个固有的异步操作(通常是I / O但不一定),你不想浪费一个线程等待袖手旁观的操作来完成。选择一个异步操作,而不是一个同步不加快操作。这将需要的时间(或甚至更多)相同的量。它只是使该线程继续执行一些其他CPU密集型工作,而不是浪费资源。

You should use async-await when you have an inherently asynchronous operation (usually I/O but not necessarily) and you don't want to waste a thread idly waiting for the operation to complete. Choosing an async operation instead of a synchronous one doesn't speed up the operation. It will take the same amount of time (or even more). It just enables that thread to continue executing some other CPU bound work instead of wasting resources.

但要能等待该操作的方法需要有一个异步一个和调用者需要的await 它等等等等。

But to be able to await that operation the method needs to be an async one and the caller needs to await it and so forth and so forth.

所以异步一路上涨,可以真正让异步调用,并释放所有的线程。如果不是异步一路那么一些线程被阻塞。

So async all the way up enables you to actually make an asynchronous call and release any threads. If it isn't async all the way then some thread is being blocked.

所以,这样的:

async Task FooAsync()
{
    await Func1();
    // do other stuff
}

async Task Func1()
{
    await Func2();
    // do other stuff
}

async Task Func2()
{
    await tcpClient.SendAsync();
    // do other stuff
}

是比这更好的:

void Foo()
{
    Func1();
    // do other stuff
}

void Func1()
{
    Func2().Wait();  // Synchronously blocking a thread.
    // do other stuff
}

async Task Func2()
{
    await tcpClient.SendAsync();
    // do other stuff
}

这篇关于为什么要使用异步/等待一路下滑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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