1
  • 情况1:
bool result = await DoAsync();
  • 案例2:
ValueTask<bool> task = DoAsync();
bool result = task.IsCompleted ? task.Result : await task;

有了case 1以上case 2
谁能说case 2性能更好(cpu,内存等)?
或者,task.IsCompleted只是重复和冗余?

4

2 回答 2

3

真正确定,您需要使用合适的基准进行测量。但是,我不认为这会产生任何重大影响,因为await 已经做到了——尽管通过GetAwaiter()(它没有分配)。它实际上会使真正的异步情况变得更糟

类似于这种优化的东西在库代码中常见,但通常用于在结果很可能在很多时候同步时完全避免状态机;例如:

var pending = DoAsync(); // note: not awaited; this is a [Value]Task[<T>]
return pending.IsCompletedSuccessfully
    ? new ValueTask<Foo>(PostProcess(pending.Result))
    : Awaited(pending);

static async ValueTask<Foo> Awaited(ValueTask<Bar> pending)
    => PostProcess(await pending.ConfigureAwait(false));

这里的关键是原始方法不在async这个场景中,所以我们只async在真正的异步路径中支付任何开销(或者在失败的情况下,标准化错误堆栈)。


这是一个sharplab.io链接,显示了此优化的情况;在右侧,您可以看到未使用的优化版本async,其结果为:

    public ValueTask<Foo> ExampleAsync()
    {
        ValueTask<Bar> pending = DoAsync();
        if (!pending.IsCompletedSuccessfully)
        {
            return <ExampleAsync>g__Awaited|0_0(pending);
        }
        return new ValueTask<Foo>(PostProcess(pending.Result));
    }

然而,该Awaited方法

    [AsyncStateMachine(typeof(<<ExampleAsync>g__Awaited|0_0>d))]
    [CompilerGenerated]
    internal static ValueTask<Foo> <ExampleAsync>g__Awaited|0_0(ValueTask<Bar> pending)
    {
        <<ExampleAsync>g__Awaited|0_0>d stateMachine = default(<<ExampleAsync>g__Awaited|0_0>d);
        stateMachine.pending = pending;
        stateMachine.<>t__builder = AsyncValueTaskMethodBuilder<Foo>.Create();
        stateMachine.<>1__state = -1;
        stateMachine.<>t__builder.Start(ref stateMachine);
        return stateMachine.<>t__builder.Task;
    }
    [StructLayout(LayoutKind.Auto)]
    [CompilerGenerated]
    private struct <<ExampleAsync>g__Awaited|0_0>d : IAsyncStateMachine
    {
        public int <>1__state;

        public AsyncValueTaskMethodBuilder<Foo> <>t__builder;

        public ValueTask<Bar> pending;

        private ConfiguredValueTaskAwaitable<Bar>.ConfiguredValueTaskAwaiter <>u__1;

        private void MoveNext()
        {
            int num = <>1__state;
            Foo result;
            try
            {
                ConfiguredValueTaskAwaitable<Bar>.ConfiguredValueTaskAwaiter awaiter;
                if (num != 0)
                {
                    awaiter = pending.ConfigureAwait(false).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(ConfiguredValueTaskAwaitable<Bar>.ConfiguredValueTaskAwaiter);
                    num = (<>1__state = -1);
                }
                result = PostProcess(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);
        }
    }
于 2020-09-09T12:55:02.113 回答
1

案例1没问题。如果您根本不使用,您将使用 task.IsCompeted await

于 2020-09-09T12:53:29.897 回答