Partager via


SPListItem.Update() not starting workflow

I had a custom list and had the OOB approval workflow attached to it and setup to run on the item update. Tried and tested the list through UI and everything seems to be as perfect as it could be.

Customer was actually trying to update the list through SharePoint Object Model and was using SPListItem.Update() method. The item column is updated but the workflow is never triggered. No matter what we were trying the workflow refused to start on item changed. Still working through the user interface of SharePoint, it was working as expected.

In mean time heard about another customer who is updating an item from a SharePoint Timer Job and the workflow is triggered properly

 

 

 

This got me thinking why it is working in Timer context and not in the console application. Both the ways we are using the exact same code:

 using(SPSite site = new SPSite(url))
{
    using(SPWeb web = site.OpenWeb())
    {
        SPList list = web.GetList(url);

        SPListItem item = list.Items[1];
        item[updateField] = DateTime.Now.ToLongDateString();
        item.Update();
    }
}

After some research found that all the workflow's and event handlers run on a different thread than the main thread. You just cannot create another Console/Windows Application and have it trigger the workflow and just quit.

Quitting the application before the asyc worker threads finish their work, causes those threads to simply abort. In case of workflow, it would seem as workflow never fired !!

So what is the fix here? Use the following line of code

 SPSite.WorkflowManager.Dispose();

 

after updating the item. So effectively the overall code becomes:

 using(SPSite site = new SPSite(url))
{
    using(SPWeb web = site.OpenWeb())
    {
        SPList list = web.GetList(url);

        SPListItem item = list.Items[1];
        item[updateField] = DateTime.Now.ToLongDateString();
        item.Update();
        site.WorkflowManager.Dispose();
    }
}

Now when I ran the console application, as expected the item updates and the workflow is triggered 1

Comments

  • Anonymous
    July 13, 2008
    PingBack from http://stevepietrek.com/2008/07/13/links-7132008/

  • Anonymous
    August 07, 2009
    Thanks a lot. This worked for ItemUpdated on a list event receiver as well.

  • Anonymous
    February 03, 2011
    THANKS!! this is exactly what I needed to know.  you just saved the day!

  • Anonymous
    June 19, 2011
    Thanks so much for posting this, it's exactly what I was after, after at least an hour researching I came across this and sure enough, it works perfectly.