Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Passing a cancellation token for subscription handlers, possible? #407

Open
lmarrero opened this issue Sep 16, 2019 · 1 comment
Open

Passing a cancellation token for subscription handlers, possible? #407

lmarrero opened this issue Sep 16, 2019 · 1 comment

Comments

@lmarrero
Copy link

Hello. Hopefully this is just a simple question.

As a quick background, the canonical example for receiving messages is:

await client.SubscribeAsync<BasicMessage>(async msg =>
{
  Console.WriteLine($"Received: {msg.Prop}.");
});

Now consider a handler where a potentially long, async operation is executed. It would be nice to pass a cancellation token to such operation. Something like this:

await client.SubscribeAsync<BasicMessage>(async (msg, cancellationToken) =>
{
  await LongOperationAsync(msg.Prop, cancellationToken);
});

Is this currently possible with some enricher? Or, do I need custom middleware? I checked the default HandlerInvocationMiddleware (relevant call pasted below) and it does not pass the cancellation token to the handler.

protected virtual async Task InvokeMessageHandler(IPipeContext context, CancellationToken token)
{
	var args = HandlerArgsFunc(context);
	var handler = MessageHandlerFunc(context);
	var acknowledgement = await handler(args);
	context.Properties.TryAdd(PipeKey.MessageAcknowledgement, acknowledgement);
	PostInvokeAction?.Invoke(context, acknowledgement);
}
@rpawlaszek
Copy link

You can pass it directly in the method:

using (var cts = new CancellationTokenSource())
{
    var token = cts.Token;
    await client.SubscribeAsync<BasicMessage>(async msg =>
    {
      await LongOperationAsync(msg.Prop, token);
    }, null, token);
};

Because if you'd expect it to be provided via (msg, cancellationToken) then what would be the source of the token? The one (I suppose) you would like to obtain would come from your code anyways.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants