There are two approaches for a service worker to process messages from an Azure Service Bus Queue:
while (!ExitRequested)
{
try
{
var message = await _queueClient.ReceiveAsync(TimeSpan.FromSeconds(1));
if (message != null)
ProcessIt(message);
}
catch (Exception ex)
{
HandleIt(ex);
}
}
or with the EAP:
var onMessageOptions = new OnMessageOptions();
onMessageOptions.ExceptionReceived += (sender, args) => HandleIt(args.Exception);
_queueClient.OnMessageAsync(ProcessIt, onMessageOptions);
WaitFor(ExitRequested);
What are advantages and disadvantages of the two approaches? Which one should be picked in which particular scenario?
ReceiveAsync
is a part of the ASB .NET client API. OnMessage
API is way the native ASB client offers to simplify creation of concurrent message pumps, allowing you a few features "out of the box" so that you don't have to handle those manually. Among those are:
These advantages can be also viewed as disadvantages when you need the flexibility and tight control over things. For example, if you need to control how message completion is performed, you'd turn auto completion off and do it yourself. But, when you need to process more than a single incoming message at a time in your callback, OnMessage API won't let you, since it's providing one message at a time, you better off with [ReceiveBatchAsync][1]
. I had a post about OnMessage API benefits you can review.
Which one should be picked in which particular scenario?
This is something you need to answer yourself based on what your requirements and architecture are going to be. If you do not require tight control over things and going to handle one message at a time (given you can execute concurrently multiple message processing), OnMessage API is an easy path to start with and ASB client does a good job. In case you need to process batches and control a lot of lower level aspects, go with MessageSender
/MessageReceiver
approach.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With