Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a CancellationToken with the Azure Service Bus Queue client?

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.

like image 564
Matt Johnson-Pint Avatar asked May 15 '14 03:05

Matt Johnson-Pint


People also ask

What can you do with CancellationToken?

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.

Which method can you use to cancel an ongoing operation that uses CancellationToken?

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.


1 Answers

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 
}
like image 136
noseratio Avatar answered Sep 21 '22 01:09

noseratio