CodeAngry
CodeAngry

Reputation: 12995

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.

Upvotes: 14

Views: 4072

Answers (3)

Bassie
Bassie

Reputation: 10400

This is now available in .NET 5:

ReadAsStringAsync(CancellationToken) 

reference

Upvotes: 8

Edward Brey
Edward Brey

Reputation: 41728

If it's OK to use the big hammer, you can dispose the HttpClient, which will shut everything down. Unlike just abandoning the unwanted call to GetStringAsync, this avoids wasting network resources, which speeds up other operations (possibly including whatever your next operation will be).

Upvotes: 0

i3arnon
i3arnon

Reputation: 116636

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);
}

Upvotes: 8

Related Questions