Daniel Vygolov
Daniel Vygolov

Reputation: 923

How to cancel a Request/Response communication with a CancellationToken in MassTransit ESB?

I have a simple masstransit request/response proof of concept. It consists of two apps: one is for message sending and the other is for message consuming. The message sending app goes like this:

var basicClient=_busControl.CreateRequestClient<IRequest,IResponse>(queueUri, timeout);
return await basicClient.Request(new Request(json), token);

The Request method takes a CancellationToken as a second optional parameter.

The message consumer has the following code:

public async Task Consume(ConsumeContext<IRequest> context)
{
      var outputJson = await _longRunningJob.Execute(context.Message.Input, context.CancellationToken);
      context.Respond(new Response(outputJson));
}

As we can see the ConsumeContext also has a CancellationToken field.

So the question is: how can I use these tokens?

In my message sending app I'd like to cancel waiting for the response, and in the message consumer I'd like to cancel waiting for the _longrunningJob completion.

  1. When I try to pass the token to the Request method and then call Cancel() on my CancellationTokenSource I expect the method to throw OperationCancelledException, but I just get the response!
  2. I've also tried to pass an already cancelled token to this method, but nothing happened.
  3. Then I've looked at Masstransit's source code and found out that token.ThrowIfCancellationIsRequested() is not called anywhere!

So, please tell me, am I doing something wrong here and there is another way to deal with CancellationTokens, or it is just a Masstransit's bug?

Upvotes: 5

Views: 3015

Answers (1)

Rob Willis
Rob Willis

Reputation: 4844

The CancellationToken that is passed into the Request is to cancel the request itself, it's not passed onto the Consumer.

We managed to Cancel the Consumer using the following approach:

  1. Add Expiry Date header to the Request (UtcNow + timeout)
  2. In the Consumer compare the ExpiryDate header to UtcNow and if it older then exit the method

Upvotes: 2

Related Questions