How to “sleep” until timeout or cancellation is requested

I just blogged about it here: CancellationToken and Thread.Sleep in Short: var cancelled = token.WaitHandle.WaitOne(TimeSpan.FromSeconds(5)); In your context: void MyFunc (CancellationToken ct) { //… // simulate some long lasting operation that should be cancelable var cancelled = ct.WaitHandle.WaitOne(TimeSpan.FromSeconds(10)); }

CancellationToken with async Dapper methods?

You are passing the cancellation token as the parameter object; that won’t work. The first async methods in dapper did not expose a cancellation token; when I tried to add them as an optional parameter (as a separate overload, to avoid breaking existing assemblies), things got very confused with “ambiguous method” compilation problems. Consequently, I … 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

NetworkStream.ReadAsync with a cancellation token never cancels

I finally found a workaround. Combine the async call with a delay task (Task.Delay) using Task.WaitAny. When the delay elapses before the io task, close the stream. This will force the task to stop. You should handle the async exception on the io task correctly. And you should add a continuation task for both the … Read more

How to make a method cancelable without it becoming ugly?

If the steps are somehow independend regarding the dataflow within the method, but can’t be executed in a parallel matter, the following approach may be better readable: void Run() { // list of actions, defines the order of execution var actions = new List<Action<CancellationToken>>() { ct => Step1(ct), ct => Step2(ct), ct => Step3(ct) }; … 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