异步编程async/await底层是怎么做到的?

本文深入探讨了.NET中的async/await关键字,揭示其作为语法糖背后的实现机制。通过反编译代码,我们可以看到async方法实际上通过实现IAsyncStateMachine的状态机进行异步操作。在示例中,异步任务通过Task.Run启动,最终在状态机中完成并打印出相关信息。
摘要由CSDN通过智能技术生成

提起.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)
            {
            }
        }
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值