重新启动 Windows.Web.Http.HttpClient 进度事件的内部取消计时器

Restart the internal cancellation timer of the Windows.Web.Http.HttpClient on progress event

    using (var httpClient = new HttpClient(filter))
    {
      using (var httpContent = new HttpStringContent(postBody, UnicodeEncoding.Utf8, content_type))
      {
        var source = new CancellationTokenSource(150000);
        HttpResponseMessage result;
        try
        {
          result = await httpClient.PostAsync(new Uri(url), httpContent).AsTask(source.Token, new Progress<HttpProgress>(
            progress =>
          {
            Debug.WriteLine("Progress");
          }));
        }
        catch (TaskCanceledException e)
        {
          return new ServerRequestResponse(RequestResponseType.Timeout);
        }
        catch (Exception e)
        {
          return new ServerRequestResponse(RequestResponseType.Failure);
        }

        var buffer = await result.Content.ReadAsBufferAsync();
        var byteArray = buffer.ToArray();
        var responseString = Encoding.UTF8.GetString(byteArray, 0, byteArray.Length);
        return new ServerRequestResponse(RequestResponseType.Success, responseString);
      }
    }

上面的代码调用了一个 post 到服务器并且有一个超时。我需要做的是在收到 Progress 调用后重新启动内部超时计数器。我需要它能够检测传输是否仍在进行或已经停止,因为有时在慢速连接上它可能需要比超时持续时间更长的时间。

是否有这样的功能,或者我需要实现自己的计时器才能手动重启它?

I need this to be able to detect if the transfer is still going

您无法检测传输是否仍在进行,IAsyncOperationWithProgress 接口仅提供 Progress 事件处理程序。您可以检测到进度 Stage.

httpResponse = await httpClient.GetAsync(requestUri).AsTask(source.Token, new Progress<HttpProgress>((Progress) =>
{
    Debug.WriteLine(Progress.BytesReceived.ToString() + "---" + Progress.Stage);
}));

但是,您无法从输出中确定完成的进度。

0------SendingHeaders
0------WaitingForResponse
0------ReceivingHeaders
0------ReceivingContent
65536------ReceivingContent
98304------ReceivingContent
98432------ReceivingContent
98432------ReceivingContent

您只能检测到从 HttpStatusCode 开始的进度。

What I need to do is restart the internal timeout counter once I receive a Progress call.

httpclient 中的默认 timeout 值为 100,000 毫秒(100 秒)。 如果请求数据超过100秒,需要手动设置超时时间。

var cts = new CancellationTokenSource();

......

cts.CancelAfter(2000);