Search code examples
azuremessage-queueazureservicebusazure-servicebus-queues

Why to use await keyword on Azure service bus processor class StartProcessingAsync method?


I'm currently going through an example demonstrating the usage of the Azure Service Bus processor class. You can find the example link

In this particular example, there is a code snippet at the bottom of the code:

// 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();

Now, I'm curious about the necessity of the await keyword on the StartProcessingAsync method.

I have also tried below code snippet and the console statement which is after StartProcessingAsync was executed before the console statement in the MessageHandler of the processor.

// 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();

Solution

  • The setup of the handlers is happening fast enough for the operation to complete and carry on to the next instruction, Console.WriteLine. Initial message receive might be taking some time and that why you’ll see output from the processor handler second and not first.

    As to why to await, if you want to fire and forget you could but you want to ensure that if exceptions are thrown during this operation are caught by your code, you need to await. If you don't await the task or explicitly check for exceptions, the exception is lost.