Search code examples
c#workflowworkflow-foundation-4

How do I Cancel or Terminate a workflow from within itself


I have a workflow that moves files around between ftp sites. It can be the case that a user deletes the files from an ftp site while the workflow is about to copy it. I can detect that the file is gone, so I want to Cancel the workflow about to do the file transfer.

I start my workflows using a factory. The factory creates a helper class (wfManager) and the helper class starts the actual workflow using WorkflowApplication.

The workflow itself determines if it should Close based on if the file has gone missing. The workflow has a reference to the wfManager that started it so calls workflowApplication.close from the wfManager

I had thought that if I use WorkflowApplication.close from the wfManager that the workflow would Close.

However, the Close times out.

What would cause the Close to time out and is there a generic way to close or terminate a workflow via code?


Solution

  • You have basically 3 options to end a worklflow:

    • Cancel
      As you have seen this waits a bit of time (so the workflow can finish whatever it is currently doing), then closes the workflow, then invoke the OnCompleted handler
    • Terminate
      This takes a reason for termination (as a param), waits a bit of time (so the workflow can finish whatever it is currently doing), then closes the workflow, then invoke the OnCompleted handler
    • Abort
      This just kills the workflow and does not call OnCompleted handler.

    MSDN references: