El Blanco's Office 2007 Blog

Wednesday, August 08, 2007

Cancelling a Running Workflow Programatically


I got asked recently how to cancel a running workflow, so I thought I'd post the solution here for everyone . . .


The first step is to get an instance of the SPWorkflow object that represents the workflow that is running on the SPListItem in question. This can be performed as follows:


foreach (SPWorkflow wf in listItem.Workflows)
{
    if (wf.ParentAssociation.BaseId == <Guid from workflow.xml>)
    {
        if (wf.InternalState == SPWorkflowState.Running)
        {
            // Need to cancel wf here . . .
        }
    }
}

Once you've got the running SPWorkflow instance as indicated above, you now need to cancel it. This is performed by calling the CancelWorkflow method of the SPWorkflowManager class passing in the SPWorkflow instance:

SPWorkflowManager.CancelWorkflow(wf);

3 Comments:

  • I've used the same code snippet but on implementing it, it throws the following exception : "Operation is not valid due to the current state of the object."
    Please help to get rid of it I can't find any solution

    By Blogger Unknown, at 5:36 am  

  • Hi Sheenu,

    Can you send me your code and I'll take a look for you - have you identified which line of code is causing the exception to be thrown ?

    Thanks,
    Chris

    By Blogger Chris White, at 6:27 pm  

  • AllowUnsafeUpdate = true on your website object ;)

    By Anonymous Anonymous, at 4:02 pm  

Post a Comment

<< Home