ref and out arguments in async method

后端 未结 2 1797
被撕碎了的回忆
被撕碎了的回忆 2020-12-14 05:47

Does anyone know why async methods are not allowed to have ref and out arguments? I\'ve done a bit or research on it but the only thin

2条回答
  •  别那么骄傲
    2020-12-14 06:06

    C# is compiled to CIL, and CIL does not support this.

    CIL does not have async natively. async methods are compiled to a class, and all (used) parameters and local variables are stored in class fields, so that when a specific method of that class is called, the code knows where to continue executing and what values the variables have.

    ref and out parameters are implemented using managed pointers, and class fields of managed pointer type are not allowed, so the compiler cannot preserve the reference passed in.

    This restriction on managed pointers in class fields prevents some nonsensical code, as explained in Jon Skeet's answer, as a managed pointer in a class field might refer to a local variable of a function that has already returned. However, this restriction is so strict that even safe and otherwise correct usage is rejected. The ref/out fields could work, if they referred to another class field, and the compiler made sure to always wrap local variables passed with ref/out in a class (like it already knows how to do).

    So, C# simply does not have any way to work around the restrictions imposed by CIL. Even if the C# designers want to allow it (I'm not saying they do), they cannot.

提交回复
热议问题