为什么在Roslyn中使用异步状态机类(而不是结构)? [英] Why are async state machines classes (and not structs) in Roslyn?

查看:63
本文介绍了为什么在Roslyn中使用异步状态机类(而不是结构)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们考虑一下这种非常简单的异步方法:

Let’s consider this very simple async method:

static async Task myMethodAsync() 
{
    await Task.Delay(500);
}

当我使用VS2013(Roslyn之前的编译器)进行编译时,生成的状态机是一个结构.

When I compile this with VS2013 (pre Roslyn compiler) the generated state-machine is a struct.

private struct <myMethodAsync>d__0 : IAsyncStateMachine
{  
    ...
    void IAsyncStateMachine.MoveNext()
    {
        ...
    }
}

当我使用VS2015(Roslyn)进行编译时,生成的代码是这样的:

When I compile it with VS2015 (Roslyn) the generated code is this:

private sealed class <myMethodAsync>d__1 : IAsyncStateMachine
{
    ...
    void IAsyncStateMachine.MoveNext()
    {
        ...
    }
}

您可以看到Roslyn生成一个类(而不是一个结构).如果我没记错的话,旧编译器中异步/等待支持的第一个实现(我猜是CTP2012)也会生成类,然后出于性能原因将其更改为struct. (在某些情况下,您可以完全避免装箱和分配堆…)(请参阅

As you can see Roslyn generates a class (and not a struct). If I remember correctly the first implementations of the async/await support in the old compiler (CTP2012 i guess) also generated classes and then it was changed to struct from performance reasons. (in some cases you can completely avoid boxing and heap allocation…) (See this)

有人知道为什么在罗斯林又改变了吗? (对此我没有任何问题,我知道此更改是透明的,不会更改任何代码的行为,我很好奇)

Does anyone know why this was changed again in Roslyn? (I don’t have any problem regarding this, I know that this change is transparent and does not change the behavior of any code, I’m just curious)

@Damien_The_Unbeliever(和源代码:))的答案得到了恕我直言. Roslyn所描述的行为仅适用于调试构建(由于注释中提到了CLR限制,因此需要这样做).在Release中,它还会生成一个结构(具有所有优点.).因此,这似乎是一个非常聪明的解决方案,可同时支持编辑"和继续"以及更好的生产性能.有趣的东西,谢谢大家参加!

The answer from @Damien_The_Unbeliever (and the source code :) ) imho explains everything. The described behaviour of Roslyn only applies for debug build (and that's needed because of the CLR limitation mentioned in the comment). In Release it also generates a struct (with all the benefits of that..). So this seems to be a very clever solution to support both Edit and Continue and better performance in production. Interesting stuff, thanks for everyone who participated!

推荐答案

我对此没有任何先见之明,但是由于Roslyn这些天都是开源的,因此我们可以遍历代码进行解释.

I didn't have any foreknowledge of this, but since Roslyn is open-source these days, we can go hunting through the code for an explanation.

>

在这里,在因此,尽管使用struct有一定的吸引力,但允许编辑并继续显然是更好的选择.

So, whilst there's some appeal to using structs, the big win of allowing Edit and Continue to work within async methods was obviously chosen as the better option.

这篇关于为什么在Roslyn中使用异步状态机类(而不是结构)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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