gpt4 book ai didi

c# - 将 GetAwaiter().GetResult() 与 ServiceBusReceiver.PeekMessagesAsync 一起使用时出现 System.InvalidOperationException

转载 作者:行者123 更新时间:2023-12-05 03:41:00 35 4
gpt4 key购买 nike

上下文

我们正在使用 GetAwaiter().GetResult(),因为 PowerShell 的 Cmdlet.ProcessRecord() 不支持异步/等待。

代码示例

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 的情况下修复它?

最佳答案

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

The following operations should never be performed on a ValueTask<TResult> instance:

• Awaiting the instance multiple times.
• Calling AsTask multiple times.
• Using .Result or .GetAwaiter().GetResult() when the operation hasn't yet completed, or using them multiple times.
• Using more than one of these techniques to consume the instance.

If you do any of the above, the results are undefined.

您可以做的是转换 ValueTask<bool>Task<bool> , 通过使用 AsTask 方法:

while (enumerator.MoveNextAsync().AsTask().GetAwaiter().GetResult())

关于c# - 将 GetAwaiter().GetResult() 与 ServiceBusReceiver.PeekMessagesAsync 一起使用时出现 System.InvalidOperationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67913032/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com