CancellationToken在Asp.Net Web Api 4.5中不起作用

时间:2016-09-28 04:35:38

标签: c# asp.net

我一直在尝试向我的web api异步控制器添加一个取消令牌,以便检测httpClient何时超时(这样我就可以停止任何挂起的等待呼叫),花费数小时就没有成功。这是我的桌面应用程序(.Net 4.0)调用web api:

public void GetServObjAsync()
{
   try
   {
      var client = new HttpClient()
      {
            Timeout = TimeSpan.FromMilliseconds(10000)
      };
      var myUri = new Uri("http://mysWebApi.net/myController");
      client.GetAsync(myUri ).ContinueWith(t =>
      {
         if (t.IsCompleted)
         {
            t.Result.Content.ReadAsAsync<servObj>().ContinueWith(t2 =>
            {
               if (!t2.IsFaulted)
               {
                  OnSerVObjReady(t2.Result);
               }
             }
          }
       }
    }
    catch
    {
       // Handle and notify
    }
}

这是我的web api控制器:

public class ServController : ApiController
{
  public async Task<servObj> Get(CancellationToken Token)
  {
     try
     {
       await Task.Delay(15000);
       var resp = await singleHttpCallAsync(Token);
       if (Token.IsCancellationRequested)
       {
          return null;
       }
       var respObj = await multipleHttpCallsAsync(Token);
       return respObj;
     }
     catch
     {
       return null;
     }
  }

  private Async Task<servObj> multipleHttpCallsAsync(CancellationToken token)
  {
    var respObjs = new List<detailObj>();
    var httpCalls = new Task<detailObj>[2];
    httpCalls[0] = singleHttpCall2Async(0, token);
    httpCalls[1] = singleHttpCall2Async(1, token);
    await Task.WhenAll(httpCalls);
    respObjs.Add(await httpCalls[0]);
    respObjs.Add(await httpCalls[1]);
    return new servObj(respObjs);
  }
}

我已经尝试了Client disconnects in ASP.NET Web API中所述的方法,其他许多方法,使用不同的超时,但最后,请求完成并返回servObj(respObjs)。任何有关httpClient.timeout未反映在我的控制器中的帮助都将不胜感激。

0 个答案:

没有答案