views:

71

answers:

2

How do you design a method/class that should support cancellation of the operation?

I realized that I never do that in a consistent manner and I want to change that.

Some of the things I have used:

  • a boolean property on the class IsCancelled that I synchronize internally. sometimes I have a CanCancel property if the operation cannot be canceled at any given time
  • pass a Func< bool > delegate that I repeatedly call to see if the operation has been canceled.
  • terminate the thread manually - although this is definitely bad practise

How do you normally do that?

+1  A: 

I'd prefer to use the IsCancelled property idea. Your background thread method can check it at the appropriate times, do any cleanup as needed, and terminate the operation. If you're using a callback method when the thread finishes, it's easy to check the property and see if it's valid or not. I've used framework worker thread classes that used this strategy in the past, and it's worked well.

Marc Charbonneau
did you ever implement this for a single method, instead of a class?The thing with the IsCancelled is that I keep reimplementing that in every class I need it. would be good to have a single implementation for this kind of thing.
Patrick Klug
+1  A: 

Go back to the use case: what is the behavior you're trying to provide? If you have an asynchronous operation that you want to cancel, then you probably can best implement a method that lets you notify the other threadt via a flag or a semaphore. Sending a signal is a nice method to get it's attention, although I haven't looked into C#'s handling of signals. If you need to be able to cancel and undo, the Command pattern comes in handy.

Charlie Martin