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);
}
}
The code above calls a post to the server and has a timeout. What I need to do is restart the internal timeout counter once I receive a Progress call. I need this to be able to detect if the transfer is still going or has stopped since sometimes on slow connections it can rightfully take more then the duration of the timeout.
Is there such a functionality or I need to implement my own timer for being able to restart it manually?
I need this to be able to detect if the transfer is still going
You could not detect if the transfer is still going and IAsyncOperationWithProgress
interface only provide Progress
event handler. You could detect progress Stage
.
httpResponse = await httpClient.GetAsync(requestUri).AsTask(source.Token, new Progress<HttpProgress>((Progress) =>
{
Debug.WriteLine(Progress.BytesReceived.ToString() + "---" + Progress.Stage);
}));
However, you could not identify the progress finished form the output.
0------SendingHeaders
0------WaitingForResponse
0------ReceivingHeaders
0------ReceivingContent
65536------ReceivingContent
98304------ReceivingContent
98432------ReceivingContent
98432------ReceivingContent
You could only detect the progress finished from HttpStatusCode
.
What I need to do is restart the internal timeout counter once I receive a Progress call.
The default timeout value is 100,000 milliseconds (100 seconds) within httpclient. If you request data for more than 100 seconds, you need to set the timeout manually.
var cts = new CancellationTokenSource();
......
cts.CancelAfter(2000);