In the Azure Service Bus queue client, I use the ReceiveBatchAsync
method to wait for a specified time to receive a batch of messages asynchronously.
var messages = await queueClient.ReceiveBatchAsync(10, TimeSpan.FromSeconds(30));
I'd like a clean shutdown of my application, so I'm implementing CancellationToken
on all of my long-running async processes, but there doesn't appear to be an overload of ReceiveBatchAsync
that is cancelable.
In other words, I'd like to do this, but I can't:
var messages = await queueClient.ReceiveBatchAsync(10, TimeSpan.FromSeconds(30),
cancellationToken);
What would be the best way to apply a CancellationToken
to a task like this that doesn't offer it directly? I don't want to wait the entire 30 seconds during shutdown.
A CancellationToken enables cooperative cancellation between threads, thread pool work items, or Task objects. You create a cancellation token by instantiating a CancellationTokenSource object, which manages cancellation tokens retrieved from its CancellationTokenSource.
The CancellationToken is used in asynchronous task. The CancellationTokenSource token is used to signal that the Task should cancel itself. In the above case, the operation will just end when cancellation is requested via Cancel() method.
You probably could use QueueClient.Abort
like this:
using (cancellationToken.Register(() => queueClient.Abort())
{
var messages = await queueClient.ReceiveBatchAsync(
10, TimeSpan.FromSeconds(30));
return messages; // or process it
}
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