小编典典

HttpClient - 任务被取消?

all

当有一个或两个任务时它工作正常,但是当我们列出多个任务时会抛出错误“任务已取消”。

在此处输入图像描述

List<Task> allTasks = new List<Task>();
allTasks.Add(....);
allTasks.Add(....);
Task.WaitAll(allTasks.ToArray(), configuration.CancellationToken);


private static Task<T> HttpClientSendAsync<T>(string url, object data, HttpMethod method, string contentType, CancellationToken token)
{
    HttpRequestMessage httpRequestMessage = new HttpRequestMessage(method, url);
    HttpClient httpClient = new HttpClient();
    httpClient.Timeout = new TimeSpan(Constants.TimeOut);

    if (data != null)
    {
        byte[] byteArray = Encoding.ASCII.GetBytes(Helper.ToJSON(data));
        MemoryStream memoryStream = new MemoryStream(byteArray);
        httpRequestMessage.Content = new StringContent(new StreamReader(memoryStream).ReadToEnd(), Encoding.UTF8, contentType);
    }

    return httpClient.SendAsync(httpRequestMessage).ContinueWith(task =>
    {
        var response = task.Result;
        return response.Content.ReadAsStringAsync().ContinueWith(stringTask =>
        {
            var json = stringTask.Result;
            return Helper.FromJSON<T>(json);
        });
    }).Unwrap();
}

阅读 107

收藏
2022-06-07

共1个答案

小编典典

TaskCanceledException抛出a 的可能原因有两个:

  1. Cancel()在任务完成之前调用CancellationTokenSource与取消令牌相关联的东西。
  2. 请求超时,即未在您指定的时间跨度内完成HttpClient.Timeout

我的猜测是超时。(如果是显式取消,您可能已经知道了。)通过检查异常,您可以更加确定:

try
{
    var response = task.Result;
}
catch (TaskCanceledException ex)
{
    // Check ex.CancellationToken.IsCancellationRequested here.
    // If false, it's pretty safe to assume it was a timeout.
}
2022-06-07