I have a web app sending messages through rebus to start long running jobs on a remote machine. I'm using the MSMQ transport. The remote worker can process 5 operations in parallel. Therefore, if the remote worker is busy, some messages could pile up in the queue until the worker can process them. Meanwhile, the user might decide to cancel a pending operation (or an executing one). What's the best strategy to handle this particular scenario when using rebus (or any bus for that matter)?
1 Answers
Well, since the queue is opaque and the endpoint will only ever get to see the messages that it actually attempts to receive, there's no way, really, to filter messages before they're received.
Depending on how important it is to you that you don't unnecessarily do work, I can think of a couple of ways to abort the processing before it commences.
One way I can think of is to take advantage of the fact that Rebus executes handlers in a handler pipeline, which means you can intercept messages before they're executed.
If your work is performed by DoWork
, you can insert a "filter" like this:
Configure.With(...)
.(...)
.Options(o => o.SpecifyOrderOfHandlers()
.First<AbortIfCancelled>()
.Then<DoWork>())
.Start();
and then your AbortIfCancelled
could look like this:
public class AbortIfCancelled : IHandleMessages<Work>
{
readonly IMessageContext _messageContext;
readonly ICancelWork _cancelWork;
public AbortIfCancelled(IMessageContext messageContext, ICancelWork cancelWork)
{
_messageContext = messageContext;
_cancelWork = cancelWork;
}
public async Task Handle(Work work)
{
if (await _cancelWork.WasCancelled(work))
{
_messageContet.AbortDispatch();
}
}
}
thus aborting the rest of the pipeline if the ICancelWork
thing returns true. You will then have to implement ICancelWork
e.g. by stuffing a bool into a database somewhere.
PS: The AbortDispatch()
function on IMessageContext
is available from 0.98.11

- 18,258
- 2
- 39
- 63
-
1Thought of something like that. Even though this introduces shared data, I guess it might be worth considering depending on the importance of doing unnecessary work, as you mentioned. I'll give it a try! Thanks again. – Bredstik Sep 17 '15 at 20:21