Cancelling a WF4 AsyncCodeActivity

Even when AsyncCodeActivity.Cancel is called, the activity will still execute the EndExecute method, so it isn't immediately obvious why a second path of execution is necessary. Implementing this method is useful only when AsyncCodeActivityContext.MarkCanceled is implemented, which in turn is useful mainly when cancellation is meaningful for the underlying operation (i.e. if work already completed can be rolled back).

In order to implement cancellation in a useful way, do the following:

  • Call AsyncCodeActivityContext.MarkCanceled to mark the activity as canceled.
  • In the Cancel method, check to see what work had already been done by the activity, and undo the work.
  • Do not duplicate effort in the Cancel and the EndExecute methods in case of cancellation, since both methods will be called.

If no work needs to be rolled back when an AsyncCodeActivity is canceled, it is not necessary to override AsyncCodeActivity.Cancel.