在异步方法中避免异步和等待

时间:2018-05-22 09:34:50

标签: c# asynchronous async-await

一个快速的问题;阅读本文:http://blog.stephencleary.com/2016/12/eliding-async-await.html

它通常告诉我,使用async / await。已经这样做了。但是,他也说你在代理任务时不必使用异步部分。

// Simple passthrough to next layer: elide.
Task<string> PassthroughAsync(int x) => _service.DoSomethingPrettyAsync(x);

// Simple overloads for a method: elide.
async Task<string> DoSomethingPrettyAsync(CancellationToken cancellationToken)
{
    ... // Core implementation, using await.
}

为什么通过时不应该使用async / await?这不是那么方便,这甚至有意义吗?

任何想法?

1 个答案:

答案 0 :(得分:4)

  

为什么在通过时不应该使用async / await?

因为您键入await的那一刻,编译器会添加一个 ton 的实现粘合剂,绝对不会为您做任何事情 - 调用者已经可以等待代理任务。

如果我添加PassthroughAsync之类的内容,但使用async / await

async Task<string> AwaitedAsync(int x) => await DoSomethingPrettyAsync(x);

然后我们可以通过编译和反编译IL来看到巨大但完全冗余的代码:

[AsyncStateMachine(typeof(<AwaitedAsync>d__1))]
private Task<string> AwaitedAsync(int x)
{
    <AwaitedAsync>d__1 <AwaitedAsync>d__ = default(<AwaitedAsync>d__1);
    <AwaitedAsync>d__.<>4__this = this;
    <AwaitedAsync>d__.x = x;
    <AwaitedAsync>d__.<>t__builder = AsyncTaskMethodBuilder<string>.Create();
    <AwaitedAsync>d__.<>1__state = -1;
    AsyncTaskMethodBuilder<string> <>t__builder = <AwaitedAsync>d__.<>t__builder;
    <>t__builder.Start(ref <AwaitedAsync>d__);
    return <AwaitedAsync>d__.<>t__builder.Task;
}
[StructLayout(LayoutKind.Auto)]
[CompilerGenerated]
private struct <AwaitedAsync>d__1 : IAsyncStateMachine
{
    public int <>1__state;

    public AsyncTaskMethodBuilder<string> <>t__builder;

    public C <>4__this;

    public int x;

    private TaskAwaiter<string> <>u__1;

    private void MoveNext()
    {
        int num = <>1__state;
        C c = <>4__this;
        string result;
        try
        {
            TaskAwaiter<string> awaiter;
            if (num != 0)
            {
                awaiter = c.DoSomethingPrettyAsync(x).GetAwaiter();
                if (!awaiter.IsCompleted)
                {
                    num = (<>1__state = 0);
                    <>u__1 = awaiter;
                    <>t__builder.AwaitUnsafeOnCompleted(ref awaiter, ref this);
                    return;
                }
            }
            else
            {
                awaiter = <>u__1;
                <>u__1 = default(TaskAwaiter<string>);
                num = (<>1__state = -1);
            }
            result = awaiter.GetResult();
        }
        catch (Exception exception)
        {
            <>1__state = -2;
            <>t__builder.SetException(exception);
            return;
        }
        <>1__state = -2;
        <>t__builder.SetResult(result);
    }

    void IAsyncStateMachine.MoveNext()
    {
        //ILSpy generated this explicit interface implementation from .override directive in MoveNext
        this.MoveNext();
    }

    [DebuggerHidden]
    private void SetStateMachine(IAsyncStateMachine stateMachine)
    {
        <>t__builder.SetStateMachine(stateMachine);
    }

    void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine)
    {
        //ILSpy generated this explicit interface implementation from .override directive in SetStateMachine
        this.SetStateMachine(stateMachine);
    }
}

现在与非async passthru汇编的内容形成鲜明对比:

private Task<string> PassthroughAsync(int x)
{
    return DoSomethingPrettyAsync(x);
}

除了绕过大量struct初始化和方法调用之外,还有一个可能的&#34;框&#34;如果它实际上是异步的(在没有完成同步的情况下它没有&#34;框&#34;),这个PassthroughAsync也将是JIT内联的一个很好的候选者,所以在实际CPU操作码中,PassthroughAsync可能甚至不存在。