Here's a (silly) example of a method that blocks the caller's thread but does not support cancellation:
Public Sub WorkUntil5()
Threading.SpinWait.SpinUntil(Function() Now.Hour >= 17)
End Sub
In the worst case scenario, calling this method takes 17 hours to return. Pretend that I don't have access to the source code of this method. How do I wrap the call in a method that takes a CancellationToken?
The goal is to let WorkUntil5()
run until cancellation is requested. At that point the call should be terminated using any means possible.
Here's the best way I could come up with myself. It uses tasks, but it still blocks the caller's thread. Something about that doesn't feel right. Thinking there should be a better way to call mres.Set()
once the first call returns.
Public Sub WorkUntilYouGetBored(cancellationToken As Threading.CancellationToken)
Dim mres As New Threading.ManualResetEventSlim
Using cancellationToken.Register(Sub() mres.Set())
Dim t = Task.Factory.StartNew(Sub() WorkUntil5())
t.ContinueWith(Sub() mres.Set())
mres.Wait()
End Using
If cancellationToken.IsCancellationRequested Then
Console.WriteLine("You went home early.")
Else
Console.WriteLine("It's time to go home.")
End If
End Sub
Let's rephrase the question. You have a non-cancelable operation called WorkUntil5 which you want to cancel. How can you do that?
Stephen Toub discusses this scenario in "How do I cancel non-cancelable async operations?".
The only real solution is to fix WorkUntil5 so that it allows cancellation. If that isn't possible (why?), you have to decide what you mean by "cancellation"?
Do you want to:
Both operations are unreliable because you have no way to know what was left unfinished in the long-running method. It's not a problem with the design of the TPL but the design of the long-running method.
Operation #1 isn't really possible, since the method doesn't provide any way to cancel it.
Operation #2 can be handled using Tasks and the TaskCompletionSource but isn't very reliable, because you have no way of knowing if the long operation left garbage behind or terminated with an exception.
Stephen Toub shows how to do this and even provides an extension method to do that: