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.

Comments (2)

  1. PaulG says:

    Can you elaborate on what you mean by 'only when AsyncCodeActivityContext.MarkCanceled is implemented'?  Who is calling MarkCancelled?  Is that something done from inside the Cancel implementation?  Or is that the method used for a container activity to cancel a child activity?

  2. That's correct- this would be called by the developer inside the Cancel implementation (since it requires access to the activity context), and sets the internal state of the executing activity to canceled. The runtime is then made aware of the activity's canceled state, and will behave appropriately in response to various events (such as persistence).