Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

eliding async and await in async methods [duplicate]

a quick question; reading this article: http://blog.stephencleary.com/2016/12/eliding-async-await.html

it generally tells me, use async/await. Allready doing that. However, he is also saying that you don't have to use the async part when you are proxying the task.

// 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.
}

why should be not use async/await when passing through? Isn't that less convenient, and does this even make sense?

any thoughts anyone?

like image 540
Roelant M Avatar asked May 22 '18 09:05

Roelant M


1 Answers

why should be not use async/await when passing through?

because the moment you type await, the compiler adds a ton of implementation glue that does absolutely nothing for you - the caller can already just await the proxied task.

If I add something like your PassthroughAsync, but with the async/await:

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

then we can see the huge but completely redundant code by compiling it and decompiling the 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);
    }
}

Now contrast to what the non-async passthru compiles to:

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

In addition to bypassing a huge amount of struct initialization and method calls, a possible "box" onto the heap if it is actually async (it doesn't "box" in the already-completed-synchronously case), this PassthroughAsync will also be a great candidate for JIT-inlining, so in the actual CPU opcodes, PassthroughAsync will probably not even exist.

like image 105
Marc Gravell Avatar answered Nov 10 '22 12:11

Marc Gravell