将每一个“等待”经营结果的状态机? [英] Will every 'await' operator result in a state machine?

查看:163
本文介绍了将每一个“等待”经营结果的状态机?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下code:

public async Task<string> GetString()
{
    //Some code here...
    var data = await A();
    //Some more code...
    return data;
}
private async Task<string> A()
{
    //Some code here..
    var data = await B();
    //manipulating data...
    return data;
}
private async Task<string> B()
{
    //Some code here..
    var data = await C();
    //manipulating data...
    return data;
}
private async Task<string> C()
{
    //Some code here..
    var data = await FetchFromDB();
    //manipulating data...
    return data;
}
private async Task<string> FetchFromDB()
{
    return await SOME_HTTP_REQUEST;
}

这code展示出一种最基本的功能 - 嵌套的异步方法。
将每个方法获得翻译成一个状态机?或者是编译器足够成熟,产生更有效的结构?
在我的一些项目,还有UI /的WebAPI和I / O调用之间〜20个方法 - 不影响权衡之间的异步等待开销(如状态机)和非阻塞线程的好处?
我的意思是,如果,例如,4个状态机(4嵌套的异步方法)的开销等于阻塞I / O(在权衡而言)为50ms,将20状态机等于更长的I / O延迟( 250毫秒)?

This code demonstrate a most basic functionality - nested async methods. Will every method get translate into a state machine? Or is the compiler sophisticated enough to generate a more efficient structure? In some of my projects, there are ~20 methods between the UI/WebAPI and the I/O call - does that affect the trade-off between the async-await overhead (such as the state machine) and the non-blocking thread benefits? I mean, if, for example, the overhead of 4 state machines (4 nested async methods) equals to 50ms of blocking I/O (in terms of trade-off), will 20 state machine be equal to longer I/O's delay (250ms)?

推荐答案

每一个方法都将有一个状态机,是的。

Every method is going to have a state machine, yes.

请了状态机的开销主要是一个对象(即和几个转到 s,这将是相当快的分配),使任何类型的执行将其删除优化是一样的不创建一个类的实例一次。

Keep in mind that the "overhead" of the state machine is primarily the allocation of one object (that and a few gotos, which are going to be quite fast), so any type of "optimization" that you perform to remove it is the same as not creating an instance of a class once.

至于它是否是成本大于做的工作同步或大或小,这就是你将需要做给你的应用程序和硬件的细节就知道肯定性能基准测试的东西。

As to whether or not it's cost is greater or less than doing the work synchronously, that's something you're going to need to do performance benchmarks on given the specifics of your application and hardware to know for sure.

这篇关于将每一个“等待”经营结果的状态机?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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