rebus-org / Rebus

:bus: Simple and lean service bus implementation for .NET
https://mookid.dk/category/rebus
Other
2.26k stars 353 forks source link

Canceling/Aborting long running Handler #1165

Closed dops0 closed 1 month ago

dops0 commented 1 month ago

Is there a way to Abort/Cancel a long running Handler?

For example, lets assume we have two incoming requests that have initiated a Saga and that the Handlers for the message are long running operations. If we want to cancel/abort one of the executions by sending in a cancelation request, can we somehow route that request to the instance of the Handler that is processing it?

Maybe its something very simple and I have overlooked it in the documentation?

asherw commented 1 month ago

You could create your own CancellationTokenSource + a task on a separate thread to check for what ever flag you need. You'll then need to periodically check the cancellation token.

Here's a basic example

var myCancellationToken = new CancellationTokenSource();
var cancellationTask = Task.Factory.StartNew(async () =>
{
    await Task.Delay(5000);
    await myCancellationToken.CancelAsync();
});

while (!myCancellationToken.IsCancellationRequested)
{
    Console.WriteLine("I'm doing a long running task...");
    await Task.Delay(1000);
}
dops0 commented 1 month ago

Thanks for the tip @asherw . I'm guessing there is nothing built into Rebus already for this and we need to manage the cancellationTokens ourselves and use them to signal a handler to stop what it is doing. Will try out this method and see how it works out in my case.

mookid8000 commented 1 month ago

I'm guessing there is nothing built into Rebus already for this and we need to manage the cancellationTokens ourselves and use them to signal a handler to stop what it is doing. Will try out this method and see how it works out in my case.

Exactly... unfortunately, Rebus cannot help you with this, so this requires a bit of creativity and CancellationToken juggling. 😅