我一直在玩 Visual Studio 14 CTP 2。这个版本的 C# vNext 允许在await
finally 块中使用关键字。
我试图弄清楚这是如何实现的。我知道这是一个实现细节,在 RTM 版本发布之前可能会发生变化,但我仍然不得不为这个功能选择我的大脑。
为了尝试理解底层编译器生成的代码,我创建了这个示例代码:
private async void button1_Click(object sender, EventArgs e)
{
try
{
}
finally
{
await MyFinallyTest();
}
}
private async Task MyFinallyTest()
{
await Task.Delay(1000);
}
这是编译器生成的类:
[CompilerGenerated]
private sealed class <button1_Click>d__1 : IAsyncStateMachine
{
public int <>1__state;
public Form1 <>4__this;
public object <>7__wrap1;
public int <>7__wrap2;
public AsyncVoidMethodBuilder <>t__builder;
public TaskAwaiter <>u__$awaiter0;
private void MoveNext()
{
int num = this.<>1__state;
try
{
TaskAwaiter awaiter;
switch (num)
{
case 1:
break;
default:
{
this.<>7__wrap1 = null;
this.<>7__wrap2 = 0;
try
{
}
catch (object obj2)
{
this.<>7__wrap1 = obj2;
}
awaiter = this.<>4__this.MyFinallyTest().GetAwaiter();
if (awaiter.IsCompleted)
{
goto Label_0096;
}
this.<>1__state = num = 1;
this.<>u__$awaiter0 = awaiter;
Form1.<button1_Click>d__1 stateMachine = this;
this.<>t__builder.AwaitUnsafeOnCompleted<TaskAwaiter, Form1.<button1_Click>d__1>(ref awaiter, ref stateMachine);
return;
}
}
awaiter = this.<>u__$awaiter0;
this.<>u__$awaiter0 = new TaskAwaiter();
this.<>1__state = num = -1;
Label_0096:
awaiter.GetResult();
awaiter = new TaskAwaiter();
object obj3 = this.<>7__wrap1;
if (obj3 != null)
{
Exception source = obj3 as Exception;
if (source <= null)
{
throw obj3;
}
ExceptionDispatchInfo.Capture(source).Throw();
}
int num1 = this.<>7__wrap2;
this.<>7__wrap1 = null;
}
catch (Exception exception2)
{
this.<>1__state = -2;
this.<>t__builder.SetException(exception2);
return;
}
this.<>1__state = -2;
this.<>t__builder.SetResult();
}
[DebuggerHidden]
private void SetStateMachine(IAsyncStateMachine stateMachine)
{
}
}
据我了解,编译器正在获取finally
代码块并将其移动到编译器生成catch
块之后。如果我们想要await
在 C# 6.0 之前完成某些事情,我们必须做的事情类似。
我看到一些我不明白的事情:
编译器以 obj2 异常的形式添加生成的
catch
块(在我的方法中不存在)catch (object obj2)
并将其内部设置object
为 obj2 异常。我不明白为什么要这样做。我创建的
finally
块不再存在。这是否意味着块awaited
内的任何代码finally
都不能“享受”我们从实际将代码放入这样的块中获得的保证?