2

语境

我们使用GetAwaiter().GetResult()是因为 PowerShellCmdlet.ProcessRecord()不支持 async/await。

代码示例

class Program
{
    static async Task Main(string[] args)
    {
        var topicPath = "some-topic";
        var subscriptionName = "some-subscription";
        var connectionString = "some-connection-string";

        var subscriptionPath = EntityNameHelper.FormatSubscriptionPath(
            topicPath,
            subscriptionName
        );

        var serviceBusClient = new ServiceBusClient(connectionString);
        var receiver = serviceBusClient.CreateReceiver(queueName: subscriptionPath);

        // This one works. :-) 
        await foreach (var item in GetMessages(receiver, maxMessagesPerFetch: 5))
        {
            Console.WriteLine("async/await: " + item);
        }

        // This one explodes.
        var enumerator = GetMessages(receiver, maxMessagesPerFetch: 5).GetAsyncEnumerator();
        while (enumerator.MoveNextAsync().GetAwaiter().GetResult())
        {
            // Unhandled exception. System.InvalidOperationException: Operation is not valid due to the current state of the object.
            //    at NonSync.IAsyncEnumerable.Program.GetMessages(ServiceBusReceiver receiver, Int32 maxMessagesPerFetch)+System.Threading.Tasks.Sources.IValueTaskSource<System.Boolean>.GetResult()
            //    at NonSync.IAsyncEnumerable.Program.Main(String[] args) in C:\dev\mediavalet\MediaValet.Learning\entropy\NonSynchronousDotNet\NonSync.IAsyncEnumerable\Program.cs:line 42
            //    at NonSync.IAsyncEnumerable.Program.<Main>(String[] args)
            Console.WriteLine("GetAwaiter().GetResult(): " + enumerator.Current);
        }
    }

    public static async IAsyncEnumerable<string> GetMessages(
        ServiceBusReceiver receiver,
        int maxMessagesPerFetch
    )
    {
        yield return "Foo";
        var messages = await receiver.PeekMessagesAsync(maxMessagesPerFetch);
        yield return "Bar";
    }
}

问题

这里发生了什么?我们如何在不改变的情况下修复它GetMessages

4

2 回答 2

1

根据ValueTask<TResult>结构的文档:

永远不应在ValueTask<TResult>实例上执行以下操作:

• 多次等待实例。•多次
调用。 •在操作尚未完成时使用或使用它们,或多次使用它们。 • 使用这些技术中的一种以上来使用实例。AsTask
.Result.GetAwaiter().GetResult()

如果您执行上述任何操作,则结果未定义。

您可以做的是使用以下方法将 转换ValueTask<bool>为 a :Task<bool>AsTask

while (enumerator.MoveNextAsync().AsTask().GetAwaiter().GetResult())
于 2021-06-10T00:18:42.837 回答
1

该答案通过代码示例补充了 Theodor 的答案。我们的具体问题是我们在完成GetResult()之前打电话ValueTask。文档指定这是不允许的:

一个 ValueTask 实例只能被等待一次,并且消费者在实例完成之前可能不会读取 Result。如果这些限制不可接受,请通过调用 AsTask 将 ValueTask 转换为 Task。(强调补充)。

using System;
using System.Collections.Generic;
using System.Threading.Tasks;

var enumerator = GetAsyncEnumerable().GetAsyncEnumerator();

while (true)
{
    var moveNext = enumerator.MoveNextAsync();
    var moveNextAwaiter = moveNext.GetAwaiter();

    Console.WriteLine("ValueTask.IsCompleted: {0}", moveNext.IsCompleted);

    try
    {
        if (moveNextAwaiter.GetResult())
        {
            Console.WriteLine("IAsyncEnumerator.Current: {0}", enumerator.Current);
            continue;
        }

        Console.WriteLine("Done! We passed the end of the collection.");
        break;
    }
    catch (InvalidOperationException)
    {
        Console.WriteLine("Boom! GetResult() before the ValueTask completed.");
        continue;
    }
}

async IAsyncEnumerable<int> GetAsyncEnumerable()
{
    yield return 1;
    await Task.Delay(1000);
    yield return 2; // <---- We never access this, because GetResult() explodes.
    yield return 3;
}

输出:

ValueTask.IsCompleted: True
IAsyncEnumerator.Current: 1

ValueTask.IsCompleted: False
Boom! GetResult() before the ValueTask completed.

ValueTask.IsCompleted: True
IAsyncEnumerator.Current: 3

ValueTask.IsCompleted: True
Done! We passed the end of the collection.
于 2021-06-10T01:03:30.513 回答