Deferred Message Processing in NServiceBus
When working on a project using NServiceBus, we came up with an interesting requirement. The messages in the queue should be processed only in certain time frames. The reason is that message handler is making a webservice call and the other party is only available at certain times and system is not even allowed to make a call during the outage window. You can easily achieve this using Bus.Defer feature in version 3.0 of NServiceBus, but that would put the message at the back of the queue and would change the order of the messages which was very important from business perspective in our case. So we had to roll up our sleeves and dig a bit deeper. It turned out NServiceBus is using an ITransport interface to process the messages in the queue. The implementation that comes with NServiceBus is named TransactionalTransport. This is the class that handles the processing threads under the hood, so what if we set the number of processing threads to zero for a while, and when we need to resume processing, set it back to the default value (one or more threads)?
Udi suggests that you shouldn’t actually use this, if possible. Instead send the message to the remote queue and let the other end worry about how and when to process it, but this may not work if you’re working in a locked down environment or your customer would simply play it by their rules.
Okay here’s the code snippet if you’re interested.
public abstract class BaseCommandHandler<T> : IHandleMessages<T>