如何在忘记令牌后突破等待base.SendAsync?

时间:2016-06-13 17:53:29

标签: c# asp.net-mvc asp.net-mvc-4 async-await

我有一个异步过程需要花费太多时间来返回结果,因此我想将取消令牌设置为3分钟。

所以,我在一段时间内取消了取消令牌,但等待base.SendAsync保持等待响应的await状态,如何在定时器打开时立即取消等待状态取消令牌已启动?

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;
        }
    }
}

3 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

虽然我同意之前的回答,但我会补充一些内容:

using(var cancelTokenSource = new System.Threading.CancellationTokenSource(System.TimeSpan.FromMinutes(3.0)))
{
...
}

Since System.Threading.CancellationTokenSource implements IDisposable

答案 2 :(得分:0)

HttpClient有一个Timeout属性,我认为行为因使用哪个底层Handler而异(通常是HttpClientHandler或WebRequestHandler)。我相信使用HttpClientHandler,您可以使用带有计时器的CancellationTokenSource来短路超时警报(在超时之前触发取消),但如果请求在取消令牌超时之前超时,您的请求将在3分钟之前取消

例如,如果您的来电者看起来像这样:

public async Task InvokeRequest()
{
    using (var cts = new CancellationTokenSource(System.TimeSpan.FromMinutes(3)))
    {
         await myHandler.SendAsync(new HttpRequestMessage { ... }, cts.Token).ConfigureAwait(false);
    }        
}

...但是HttpClient.Timeout是100秒(我认为是默认值),请求将在100秒取消,而不是180秒。

有关详细信息,请参阅此问题: Whats the difference between HttpClient.Timeout and using the WebRequestHandler timeout properties?