为什么要在Azure服务总线处理器类StartProcessingAsync方法上使用await关键字?

问题描述 投票:0回答:1

我当前正在通过一个示例演示 Azure 服务总线处理器类的用法。你可以找到例子 链接

在这个特定的例子中,代码底部有一个代码片段:

// start processing
await processor.StartProcessingAsync();    
// since the processing happens in the background, we add a Console.ReadKey to allow the processing to continue until a key is pressed.
Console.ReadKey();

现在,我很好奇 StartProcessingAsync 方法上的await关键字的必要性。

我还尝试了下面的代码片段和在处理器的MessageHandler中的控制台语句之前执行StartProcessingAsync之后的控制台语句。

// start processing
await processor.StartProcessingAsync();    
// since the processing happens in the background, we add a Console.ReadKey to allow the processing to continue until a key is pressed.
Console.WriteLine("Executed before the console statement in the processors message handler method.");
Console.ReadKey();
azure message-queue azureservicebus azure-servicebus-queues
1个回答
0
投票

处理程序的设置速度足够快,足以完成操作并继续执行下一条指令,

Console.WriteLine
。初始消息接收可能需要一些时间,这就是为什么您会在第二个而不是第一个看到处理器处理程序的输出。

至于为什么要等待,如果你想解雇并忘记你可以,但你想确保如果在此操作期间抛出的异常被你的代码捕获,你需要等待。如果您不等待任务或显式检查异常,则异常将丢失。

© www.soinside.com 2019 - 2024. All rights reserved.