Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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);
–
–
–
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.