Can I cancel StreamReader.ReadLineAsync with a CancellationToken?

.NET 6 brings Task.WaitAsync(CancellationToken). So one can write: using StreamReader reader = new StreamReader(dataStream); while (!reader.EndOfStream) { Console.WriteLine(await reader.ReadLineAsync().WaitAsync(cancellationToken).ConfigureAwait(false)); } In .NET 7 (not yet released), it should be possible to write simply: using StreamReader reader = new StreamReader(dataStream); while (!reader.EndOfStream) { Console.WriteLine(await reader.ReadLineAsync(cancellationToken).ConfigureAwait(false); } based on https://github.com/dotnet/runtime/issues/20824 and https://github.com/dotnet/runtime/pull/61898.

Faulted vs Canceled task status after CancellationToken.ThrowIfCancellationRequested

There are two problems here. First, it’s always a good idea to pass CancellationToken to the Task.Run API, besides making it available to the task’s lambda. Doing so associates the token with the task and is vital for the correct propagation of the cancellation triggered by token.ThrowIfCancellationRequested. This however doesn’t explain why the cancellation status … Read more

Why CancellationToken is separate from CancellationTokenSource?

I was involved in the design and implementation of these classes. The short answer is “separation of concerns“. It is quite true that there are various implementation strategies and that some are simpler at least regarding the type system and initial learning. However, CTS and CT are intended for use in a great many scenarios … Read more

Using CancellationToken for timeout in Task.Run does not work [duplicate]

Cancellation in Managed Threads: Cancellation is cooperative and is not forced on the listener. The listener determines how to gracefully terminate in response to a cancellation request. You didn’t write any code inside your Task.Run method to access your CancellationToken and to implement cancellation – so you effectively ignored the request for cancellation and ran … Read more

How to use the CancellationToken without throwing/catching an exception?

You can implement your work method as follows: private static void Work(CancellationToken cancelToken) { while (true) { if(cancelToken.IsCancellationRequested) { return; } Console.Write(“345”); } } That’s it. You always need to handle cancellation by yourself – exit from method when it is appropriate time to exit (so that your work and data is in consistent state) … Read more

GetResponseAsync does not accept cancellationToken

Something like this should work (untested): public static class Extensions { public static async Task<HttpWebResponse> GetResponseAsync(this HttpWebRequest request, CancellationToken ct) { using (ct.Register(() => request.Abort(), useSynchronizationContext: false)) { var response = await request.GetResponseAsync(); ct.ThrowIfCancellationRequested(); return (HttpWebResponse)response; } } } In theory, if cancellation is requested on ct and request.Abort is invoked, await request.GetResponseAsync() should throw … Read more

Async network operations never finish

So i’ve made an extension method on IDisposable that creates a CancellationToken that disposes the connection on timeout, so the task finishes and everything carries on: public static IDisposable CreateTimeoutScope(this IDisposable disposable, TimeSpan timeSpan) { var cancellationTokenSource = new CancellationTokenSource(timeSpan); var cancellationTokenRegistration = cancellationTokenSource.Token.Register(disposable.Dispose); return new DisposableScope( () => { cancellationTokenRegistration.Dispose(); cancellationTokenSource.Dispose(); disposable.Dispose(); }); } … Read more

How to use the CancellationToken property?

You can implement your work method as follows: private static void Work(CancellationToken cancelToken) { while (true) { if(cancelToken.IsCancellationRequested) { return; } Console.Write(“345”); } } That’s it. You always need to handle cancellation by yourself – exit from method when it is appropriate time to exit (so that your work and data is in consistent state) … Read more

Cancellation token in Task constructor: why?

Passing a CancellationToken into the Task constructor associates it with the task. Quoting Stephen Toub’s answer from MSDN: This has two primary benefits: If the token has cancellation requested prior to the Task starting to execute, the Task won’t execute. Rather than transitioning to Running, it’ll immediately transition to Canceled. This avoids the costs of … Read more