编译器是否执行​​"返回值优化"对异步方法链 [英] Does compiler perform "return value optimization" on chains of async methods

查看:115
本文介绍了编译器是否执行​​"返回值优化"对异步方法链的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不归传统意义上的价值优化,但是当你有这样的情况我想知道:

Not return value optimization in the traditional sense, but I was wondering when you have a situation like this:

private async Task Method1()
{
    await Method2();
}

private async Task Method2()
{
    await Method3();
}

private async Task Method3()
{
    //do something async
}

这可以明显地更优化写入:

This could obviously be written more optimally:

private Task Method1()
{
    return Method2();
}

private Task Method2()
{
    return Method3();
}

private async Task Method3()
{
    //do something async
}

我只是想知道是否有人知道,如果(MS)编译器足够聪明不生成状态机方法一()方法2()一审

推荐答案

没有,C#编译器不会优化它,它的不应该的。这是概念上两个不同的东西,这里是一个类似的问题

No, the C# compiler doesn't optimize it and it should not. These are conceptually two different things, here is a similar question.

IMO,主要的区别是例外过得好将会传播到方法1 方法2 的调用者。我这里 demo'ed这behavoir

IMO, the major difference is in how exceptions are getting propogated into the caller of Method1 and Method2. I demo'ed this behavoir here.

在第一种情况下(不带状态机),一个异常会的立即的抛出的调用者的堆栈帧。如果是unhanded,应用程序可能会崩溃的时候了(除非有另一个异步在同一个堆栈帧的调用链方法)。

In the first case (without the state machine), an exception will be immediately thrown on the caller's stack frame. If it is unhanded, the app may crash right away (unless there is another async method in the chain of calls on the same stack frame).

在第二种情况下(使用状态机),破例将保持的休眠的在工作对象返回给调用者,直到它通过观察等待任务 task.Wait(),一段时间后。它可能会得到完全不同的堆栈帧上观察到的,或者可能根本不得到遵守。我贴这个一些细节这里

In the second case (with the state machine), an exception will remain dormant in the Task object returned to the caller, until it is observed via await task or task.Wait(), some time later. It may get observed on a completely different stack frame, or may not get observed at all. I posted some more details about this here.

这篇关于编译器是否执行​​"返回值优化"对异步方法链的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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