提起.Net中的 async/await,相信很多.neter 第一反应都会是异步编程,其本质是语法糖,但继续追查下去,既然是语法糖,那么经过编译之后,真正的代码是什么样的,如何执行的?带着这些疑问,通过网上资料的查询,可以了解到编译之后,是通过实现 IAsyncStateMachine 的一个状态机来实现的.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Asnyc();
Console.WriteLine("主程序代码执行");
}
static async Task Asnyc()
{
await Task.Run(() => { Thread.Sleep(500);Console.WriteLine("异步代码运行中");});
Console.WriteLine("异步代码已完成");
}
}
}
使用net reflector反编译:
namespace ConsoleApp1
{
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
internal class Program
{
[AsyncStateMachine(typeof(<Asnyc>d__1)), DebuggerStepThrough]
private static Task Asnyc()
{
<Asnyc>d__1 d__ = new <Asnyc>d__1 {
<>t__builder = AsyncTaskMethodBuilder.Create(),
<>1__state = -1
};
d__.<>t__builder.Start<<Asnyc>d__1>(ref d__);
return d__.<>t__builder.get_Task();
}
private static void Main(string[] args)
{
Asnyc();
Console.WriteLine("主程序代码执行");
}
[Serializable, CompilerGenerated]
private sealed class <>c
{
public static readonly Program.<>c <>9 = new Program.<>c();
public static Action <>9__1_0;
internal void <Asnyc>b__1_0()
{
Thread.Sleep(500);
Console.WriteLine("异步代码运行中");
}
}
[CompilerGenerated]
private sealed class <Asnyc>d__1 : IAsyncStateMachine
{
public int <>1__state;
public AsyncTaskMethodBuilder <>t__builder;
private TaskAwaiter <>u__1;
private void MoveNext()
{
int num = this.<>1__state;
try
{
TaskAwaiter awaiter;
if (num != 0)
{
awaiter = Task.Run(Program.<>c.<>9__1_0 ??
(Program.<>c.<>9__1_0 = new Action(Program.<>c.<>9,
(IntPtr) this.<Asnyc>b__1_0))).GetAwaiter();
if (!awaiter.get_IsCompleted())
{
this.<>1__state = num = 0;
this.<>u__1 = awaiter;
Program.<Asnyc>d__1 d__ = this;
this.<>t__builder.AwaitUnsafeOnCompleted<TaskAwaiter,
Program.<Asnyc>d__1>(ref awaiter, ref d__);
return;
}
}
else
{
awaiter = this.<>u__1;
this.<>u__1 = new TaskAwaiter();
this.<>1__state = num = -1;
}
awaiter.GetResult();
Console.WriteLine("异步代码已完成");
}
catch (Exception exception)
{
this.<>1__state = -2;
this.<>t__builder.SetException(exception);
return;
}
this.<>1__state = -2;
this.<>t__builder.SetResult();
}
[DebuggerHidden]
private void SetStateMachine(IAsyncStateMachine stateMachine)
{
}
}
}
}