Why are async state machines classes (and not structs) in Roslyn?

后端 未结 2 1080
温柔的废话
温柔的废话 2020-12-23 15:39

Let’s consider this very simple async method:

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

When I compile this with VS

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-23 16:15

    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.

    And here, on line 60 of the AsyncRewriter, we find:

    // The CLR doesn't support adding fields to structs, so in order to enable EnC in an async method we need to generate a class.
    var typeKind = compilationState.Compilation.Options.EnableEditAndContinue ? TypeKind.Class : TypeKind.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.

提交回复
热议问题