rebus-org / Rebus.AzureServiceBus

:bus: Azure Service Bus transport for Rebus
https://mookid.dk/category/rebus
Other
33 stars 20 forks source link

Abort handler when timeout peek lock #64

Closed marmagni closed 3 years ago

marmagni commented 3 years ago

Hi,

It's possible to abort my handler processing when my configured peek lock time out?

mookid8000 commented 3 years ago

Yes.... but you need to do it yourself 🙂

But... you DO know Rebus can automatically renew the peek lock for you while your message handler is running, right?

Configure.With(...)
    .Transport(t => t.UseAzureServiceBus(connectionString, "queue")
                     .AutomaticallyRenewPeekLock())
    .(...)

If you want to cancel your logic instead, you can do something like this:

public class YourMessageHandler : IHandleMessages<YourMessage>
{
    public async Task Handle(YourMessage message) 
    {   
        using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromMinutes(1));

        var token = cancellationTokenSource.Token;

        await HandleWithTimeout(message, token);
    }

    async Task HandleWithTimeout(YourMessage message, CancellationToken cancellationToken)
    {
        // do your thing here - pass cancellationToken to awaited calls,
        // call 
        //      cancellationToken.ThrowIfCancellationRequested()
        // or check
        //      cancellationToken.IsCancellationRequested
        // when it makes sense
    }
}

(see here: https://github.com/rebus-org/Rebus/wiki/Azure-Service-Bus-transport#long-running-message-handlers )