async 和 await 之本质
反编译,大概过程是:
- 创建一个结构体保存这个任务需要的内容,包括委托,状态标记,TaskAwaiter
- 通过Task.Run执行异步方法,之后持续对Task状态进行判断。
- 当执行完毕后通过task.GetResult()获取返回值。
剩余疑问:
- MoveNext应该是持续调用的,但不知道谁在调用。
- 异步执行完毕后执行主线程剩余代码,是如何返回主线程的(还是一直就是在主线程上执行?为何不造成阻塞)
internal class Program
{
// Methods
[AsyncStateMachine(typeof(<Async2>d__2)), DebuggerStepThrough]
private static void Async2()
{
<Async2>d__2 d__;
d__.<>t__builder = AsyncVoidMethodBuilder.Create();
d__.<>1__state = -1;
d__.<>t__builder.Start<<Async2>d__2>(ref d__);
}
private static void Main(string[] args)
{
Async2();
Console.WriteLine("aaa");
Console.ReadLine();
}
// Nested Types
[CompilerGenerated]
private struct <Async2>d__2 : IAsyncStateMachine
{
// Fields
public int <>1__state;
public AsyncVoidMethodBuilder <>t__builder;
private object <>t__stack;
private TaskAwaiter <>u__$awaiter3;
// Methods
private void MoveNext()
{
try
{
TaskAwaiter awaiter;
bool flag = true;
switch (this.<>1__state)
{
case -3:
goto Label_00C5;
case 0:
break;
default:
if (Program.CS$<>9__CachedAnonymousMethodDelegate1 == null)
{
Program.CS$<>9__CachedAnonymousMethodDelegate1 = new Action(Program.<Async2>b__0);
}
awaiter = Task.Run(Program.CS$<>9__CachedAnonymousMethodDelegate1).GetAwaiter();
if (awaiter.IsCompleted)
{
goto Label_0090;
}
this.<>1__state = 0;
this.<>u__$awaiter3 = awaiter;
this.<>t__builder.AwaitUnsafeOnCompleted<TaskAwaiter, Program.<Async2>d__2>(ref awaiter, ref this);
flag = false;
return;
}
awaiter = this.<>u__$awaiter3;
this.<>u__$awaiter3 = new TaskAwaiter();
this.<>1__state = -1;
Label_0090:
awaiter.GetResult();
awaiter = new TaskAwaiter();
Console.WriteLine("ccc");
}
catch (Exception exception)
{
this.<>1__state = -2;
this.<>t__builder.SetException(exception);
return;
}
Label_00C5:
this.<>1__state = -2;
this.<>t__builder.SetResult();
}
[DebuggerHidden]
private void SetStateMachine(IAsyncStateMachine param0)
{
this.<>t__builder.SetStateMachine(param0);
}
}
public delegate int MyDelegate(int x);
}
欢迎C#或Winform技术交流,C#交流群:83868794