语境
我们使用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
?