让我们考虑一下这个非常简单的异步方法:
static async Task myMethodAsync()
{
await Task.Delay(500);
}
当我用 VS2013(前 Roslyn 编译器)编译这个时,生成的状态机是一个 struct。
private struct <myMethodAsync>d__0 : IAsyncStateMachine
{
...
void IAsyncStateMachine.MoveNext()
{
...
}
}
当我用 VS2015(Roslyn)编译它时,生成的代码如下:
private sealed class <myMethodAsync>d__1 : IAsyncStateMachine
{
...
void IAsyncStateMachine.MoveNext()
{
...
}
}
正如您所看到的,Roslyn 生成一个类(而不是一个 struct)。如果我没有记错的话,旧编译器(CTP2012)中第一个异步/等待支持的实现也生成了类,然后由于性能原因将其改为 struct。(在某些情况下,您可以完全避免装箱和堆分配...)(参见 这个)
有人知道为什么罗斯林又发生了变化吗?(我对此没有任何问题,我知道这个更改是透明的,不会改变任何代码的行为,我只是好奇)
编辑:
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!