Make Your Asynchronous C# Code Cancellable

Today asynchronous programming is everywhere. It’s hard to find software which doesn’t perform asynchronous operations. Many async operations can take a long time to finish. Sometimes they can last infinitely. This situation dictates the necessity to have a possibility to cancel operations. And this is the topic we are going to talk about: cancelling operations.

When I was a newcomer I faced with a chunk of long-running code that didn’t support cancellation. I needed to cancel it somehow. Unfortunately, I had no access to that code, so I couldn’t modify it. I was struggling with the requirement to be able to cancel that code. I was thinking about the problem for two days as I remember and I couldn’t believe that it’s actually not possible to cancel random code. Yes, there is the Thread.Abort method presented since .NET 1, but it’s strongly not recommended to use it, because we can’t predict what will happen to the code which is going to be aborted. It’s even almost (or absolutely) impossible to write code which is reliable in case it is aborted by Thread.Abort, because it’s even not guaranteed that your finally-blocks will be executed. One will say that I’m talking about self-evident things, but I’ve heard many times from developers exclamations like, “why we can’t simply use Thread.Abort in order to interrupt that function?” That’s why I decided to write this post, showing how simple it is to write cancellable code.

Continue reading

UpdateableSpin Synchronization Primitive

Today we are going to look at a relatively rare case of synchronization. There are no appropriate C# synchronization primitives out of the box.
In order to understand the case we’re going to talk about you can imagine the following case: “Your code makes a call to the third-party library’s method and you have to wait that method until the end. That method performs a sequence of operations and at each step it will invoke a callback. In addition, by the agreement that method takes a timeout which is a max amount of time allocated for each step. After a callback is invoked, timeout will be reset. If you passed in 60 seconds as a timeout, then that third-party’s method will take 60 seconds for each step (if there are three steps, then 3*60 sec. is a maximum time amount may be spent on the overall execution).”

Continue reading