1

i have created custom delegating handler and override it's method

Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)

now in that method i run custom synchronous method, can you guys let me know which of this examples is correct one, or if both are not correct let me know the better usage, to avoid any deadlocks

1.

 protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        if (Processor.CanProcess(request))
        {
            var tsc = new TaskCompletionSource<HttpResponseMessage>(cancellationToken);
            tsc.SetResult(Processor.Process(request));
            return tsc.Task;
        }
        return base.SendAsync(request, cancellationToken);
    }

2.

 protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        if (Processor.CanProcess(request))
            return Task.Run(() => Processor.Process(request), cancellationToken);
        return base.SendAsync(request, cancellationToken);
    }

and should i use async await or it is better to leave as it is.

  • How often does `Processor.Process` run per second? If not often then it does not matter what you do and you can chose the most convenient form. – usr Nov 06 '16 at 14:26
  • in worst case scenario it can run every 60ms, and it can receive 16 requests at same time – Danijel Perić Nov 06 '16 at 14:51

1 Answers1

0

How often does Processor.Process run per second? If not often then it does not matter what you do and you can chose the most convenient form.

in worst case scenario it can run every 60ms, and it can receive 16 requests at same time

That's nothing. I'd be unconcerned. Also, since you don't have an async API available there's not much you can do.

Chose the most convenient form. I like this one:

return Task.FromResult(Processor.Process(request));

The cancellation token does not have any effect here so just leave it out. There's no cancellation without cooperation from Processor.

usr
  • 168,620
  • 35
  • 240
  • 369