1.同步与异步

   假设存在

   io事件a:请求网络资源 (完成耗时5s)

   io事件b:查询数据库 (完成耗时5s)

   情况一:线程1工人在发起a请求后,一直阻塞等待,在a响应返回结果后再接着处理事件b,那总共需要耗时>10s.

   情况二:线程1工人在发起a请求后,马上返回发起b请求然后返回,5s后事件a响应返回,接着事件b响应返回,那总共需要耗时<10s.

   情况一就是同步的概念,而情况二就是异步的概念。细节会有所不同,但大致上可以这样理解。然而并不是所有情况适用异步,下面将会解释。

2.异步运行的顺序

   c#中的异步关键词是async与await,常常结合task使用,如下面实例,看看它执行的情况

 static async task main(string[] args)
        {
            console.writeline($"{thread.currentthread.managedthreadid}:mainstart"); //标记1
            await sayhi();
            console.writeline($"{thread.currentthread.managedthreadid}:mainend"); //标记4
        }


        static async task sayhi()
        {
            console.writeline($"{thread.currentthread.managedthreadid}:sayhistart"); //标记2
            await task.delay(1000);
            console.writeline($"{thread.currentthread.managedthreadid}:sayhiend"); //标记3
        }

 

结果:

1:mainstart
1:sayhistart
5:sayhiend
5:mainend

 

c#7.1后的版本都支持异步main方法,程序执行的状况 

线程1->标记1,

线程1->标记2,

线程5->标记3

线程5->标记4

执行顺序如预期,而需要关注的是线程在执行期间的切换,在线程1执行完标记2后就已经返回,接着由线程5接管了后面代码逻辑的执行,那到底为什么会发生这样的情况?

答案是:编译器会自动地替我们完成了大量了不起的工作,下面接着来看看。

 

3.生成骨架与状态机

 编译器在遇到await关键字会自动构建骨架与生成状态机,按照以上例子来看看编译器做的工作有那些。

[debuggerstepthrough]
private static void <main>(string[] args)
{
    main(args).getawaiter().getresult();
}

[asyncstatemachine((type) typeof(<main>d__0)), debuggerstepthrough]
private static task main(string[] args)
{
    <main>d__0 statemachine = new <main>d__0 {
        args = args,
        <>t__builder = asynctaskmethodbuilder.create(),
        <>1__state = -1
    };
    statemachine.<>t__builder.start<<main>d__0>(ref statemachine);
    return statemachine.<>t__builder.get_task();
}

[asyncstatemachine((type) typeof(<sayhi>d__1)), debuggerstepthrough]
private static task sayhi()
{
    <sayhi>d__1 statemachine = new <sayhi>d__1 {
        <>t__builder = asynctaskmethodbuilder.create(), //如果返回的是void builder为asyncvoidmethodbuilder
        <>1__state = -1  //状态初始化为-1
    };
    statemachine.<>t__builder.start<<sayhi>d__1>(ref statemachine); //开始执行 传入状态机的引用
    return statemachine.<>t__builder.get_task(); //返回结果
}

1.编译器会自动生成void mian程序入口方法,它会调用async task main方法。(所以说c#7.1支持异步main方法,其实只是编译器做了一点小工作)

2.main方法里的输出内容与调用sayhi方法代码消失了,取而代之的是编译器生成了骨架方法,初始化 <main>d__0 状态机,把状态机的状态字段<>1__state

初始化为-1,builder为asynctaskmethodbuilder实例,接着调用builder的start方法。

3.sayhi方法同2

接着看看asynctaskmethodbuilder的start方法

[debuggerstepthrough]
public static void start<tstatemachine>(ref tstatemachine statemachine) where tstatemachine: iasyncstatemachine
{
    if (((tstatemachine) statemachine) == null)
    {
        throwhelper.throwargumentnullexception(exceptionargument.statemachine);
    }
    thread currentthread = thread.currentthread;
    thread thread2 = currentthread;
    executioncontext context2 = currentthread._executioncontext;
    synchronizationcontext context3 = currentthread._synchronizationcontext;
    try
    {
        statemachine.movenext(); //调用了状态机的movenext方法
    }
    finally
    {
        synchronizationcontext context4 = context3;
        thread thread3 = thread2;
        if (!referenceequals(context4, thread3._synchronizationcontext))
        {
            thread3._synchronizationcontext = context4;
        }
        executioncontext contexttorestore = context2;
        executioncontext currentcontext = thread3._executioncontext;
        if (!referenceequals(contexttorestore, currentcontext))
        {
            executioncontext.restorechangedcontexttothread(thread3, contexttorestore, currentcontext);
        }
    }
}

start方法调用了状态机的movenext方法,是不是很熟悉?接下来看看状态机长什么样子。

[compilergenerated]
private sealed class <main>d__0 : iasyncstatemachine
{
    // fields
    public int <>1__state;
    public asynctaskmethodbuilder <>t__builder;
    public string[] args;
    private taskawaiter <>u__1;

    // methods
    private void movenext()
    {
        int num = this.<>1__state;
        try
        {
            taskawaiter awaiter;
            if (num == 0)
            {
                awaiter = this.<>u__1;
                this.<>u__1 = new taskawaiter();
                this.<>1__state = num = -1;
                goto tr_0004;
            }
            else  //1: <>1_state初始值为-1,所以先进到该分支,由线程1执行
            {
                console.writeline($"{(int) thread.get_currentthread().managedthreadid}:mainstart"); //标记1 //线程1执行  所以输出  1:mainstart
                awaiter = program.sayhi().getawaiter(); //重点:获取taskd getawaiter方法返回taskawaiter
                if (awaiter.iscompleted) //重点:判断任务是否已经完成 
                {
                    goto tr_0004; //sayhi方法是延时任务,所以正常情况下不会跳进这里
                }
                else
                {
                    this.<>1__state = num = 0; //赋值状态0
                    this.<>u__1 = awaiter;   
                    program.<main>d__0 statemachine = this;
                    this.<>t__builder.awaitunsafeoncompleted<taskawaiter, program.<main>d__0>(ref awaiter, ref statemachine); //重点:把taskawaiter与该状态机,线程1执行到这返回           
}
}
                 return;
tr_0004:
awaiter.getresult(); //重点:获取结果 由线程1执行或延时任务不定线程执行
console.writeline($"{(int) thread.get_currentthread().managedthreadid}:mainend"); //标记4 所以输出 5:mainend

this.<>1__state = -2; this.<>t__builder.setresult();//设置结果
}
catch (exception exception)
{
this.<>1__state = -2;
this.<>t__builder.setexception(exception); //设置异常
}
}
[debuggerhidden] private void setstatemachine(iasyncstatemachine statemachine) { } }

上面我圈了重点的是关于task类型能实现async await的关键操作, 

1.线程1执行调用task实例的getawaiter方法返回taskawaiter实例。

2.判断taskawaiter实例的iscompleted属性是否完成,如果已完成,跳转到tr_0004,否则执行到awaitunsafeoncompleted方法,线程1结束返回。

我们继续来看看awaitunsafeoncompleted方法,没反编译出来,所以我们来看看与它类似的awaitoncompleted方法( awaitunsafeoncompleted实际上会调用unsafeoncompleted方法)

public void awaitoncompleted<tawaiter, tstatemachine>(ref tawaiter awaiter, ref tstatemachine statemachine) where tawaiter: inotifycompletion where tstatemachine: iasyncstatemachine
{
    try
    {
        awaiter.oncompleted(this.getstatemachinebox<tstatemachine>(ref statemachine).movenextaction);
    }
    catch (exception exception1)
    {
        task.throwasync(exception1, null);
    }
}

 

看到这里是不是豁然开朗了

1.注册taskawaiter实例完成任务的回调方法,等任务完成后将会调用状态机的movenext方法,由上篇文章task的启动方式知道后面的操作将会交由线程池的线程处理。所以标记3跟标记4将会在空闲的线程上执行。

2.<>1__state为0,跳到tr_0004执行,调用taskawaiter实例的getresult()方法,执行await后面的代码,返回结果。

sayhi方法同上。

结论

编译器遇到await后会自动构建骨架与状态机,把await后面的代码挪到任务完成的后面继续执行。主线程第一次调用movenext方法时,如果任务已经完成会直接执行后面的操作,否则直接返回,不阻塞主线程的运行。后面的流程

将交由线程池来调度完成。

回到文章开头的问题,什么情况下不适用异步?

可以看出来,使用异步编译器会生成大量额外的操作,而不耗时或者cpu密集型工作使用异步就是添堵。

 

思考

是不是只有task才能用async与await?

下一篇我将来探讨一下这个问题,感兴趣的小伙伴可以关注留意后续更新

有说得不对的地方欢迎大神指正,欢迎讨论,共同进步