I use SendAsync
with HttpCompletionOption.ResponseHeadersRead
to get the headers first. Next I check the Content-Type
and Content-Length
to make sure the response is markup and the size is decent. I use a CancellationTokenSource
to cancel the SendAsync
if it exceeds a certain timespan.
But then, if the type and size are correct, I continue to actually fetch the markup string with ReadAsStringAsync
. Can I add a cancellation token to this call? So if the actual download takes too long, I can abort it. Or can this be done in any other way?
I don't want to use GetStringAsync
as I use a custom HttpRequestMessage
.
PS: I'm rather new to C#, 2 weeks. Something might be eluding me.
No, you can't. There's no overload of ReadAsStringAsync
that accepts a cancellation token and you can't cancel a non-cancelable async operation.
You can however abandon that operation and move on with a WithCancellation
extension method, which won't actually cancel the operation but will let the code flow as if it has been:
static Task<T> WithCancellation<T>(this Task<T> task, CancellationToken cancellationToken)
{
return task.IsCompleted
? task
: task.ContinueWith(
completedTask => completedTask.GetAwaiter().GetResult(),
cancellationToken,
TaskContinuationOptions.ExecuteSynchronously,
TaskScheduler.Default);
}
This is now available in .NET 5:
ReadAsStringAsync(CancellationToken)
reference
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With