I have a asynchronous process that is taking too much time to return results, so I want to set the cancellation token to 3 minutes.
So, I have the cancellation token cancelling at a set amount of time, but the await base.SendAsync stays in the await state waiting for a response, how do I break out of that await state as soon as the the timer on the cancellation token is up?
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Net;
namespace MyModel.Models
{
public class MyHandler : DelegatingHandler
{
protected async override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
var response = new HttpResponseMessage();
bool isCancelled = false;
using (var cts = new CancellationTokenSource(System.TimeSpan.FromSeconds(15))) //just an example, so I will change to 3 minutes in future.
{
response = await base.SendAsync(request, cts.Token).ConfigureAwait(false);
if(cts.Token.IsCancellationRequested) isCancelled = true;
}
if ((response.StatusCode != HttpStatusCode.NotFound) && (!isCancelled))
{
//do work
}
return response;
}
}
}