Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Net.HttpClient Cancel ReadAsStringAsync?

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.

like image 864
CodeAngry Avatar asked Aug 09 '14 13:08

CodeAngry


2 Answers

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);
}
like image 84
i3arnon Avatar answered Oct 09 '22 18:10

i3arnon


This is now available in .NET 5:

ReadAsStringAsync(CancellationToken) 

reference

like image 41
Bassie Avatar answered Oct 09 '22 18:10

Bassie