When a SharePoint workflow is started through the Web client, the workflow is loaded in the memory of w3wp.exe until the workflow becomes idle and dehydrates to the SharePoint database. When the same workflow instance is rehydrated again, it is loaded in owstimer.exe. A SharePoint workflow can be started manually or it can be automatically started when an item is added or an existing item is changed in a list or a document library. Regardless of how a workflow is started, I always thought the memory management for loading a SharePoint workflow should be similar to what is stated above.
Some time ago, one of my colleagues, Jonas Nilsson, asked me that if a console application adds an item to a list, could the automatically started workflow on that list get loaded in the console application’s memory? My first reaction was that this wouldn’t be possible because the console application is not hosting the workflow, but is simply adding items to the list. I was counting on the timer service to load and run the workflow in this case. Well, experimentation showed that the timer service is not the hard working fellow in this case.
I wrote a few lines in a console application to add a file to a shared documents library which automatically started a workflow when an item was added to the library:
The result? The item was added to the list, but the workflow was not triggered.
I then modified the code adding a line, Console.ReadLine(), at the end to pause the console application until some user input had been received:
The result? If the user does not type any input into the application, the item is added, the workflow is triggered, and begins running.
The SharePoint log file logged two entries in the second experienment:
11/17/2010 22:51:30.73 ConsoleAddFileToList.vshost.exe (0x030C) 0x1390 SharePoint Foundation Monitoring b4ly High Leaving Monitored Scope (FireWorkflowStartingEvent). Execution Time=1.61752401492368
11/17/2010 22:51:37.26 ConsoleAddFileToList.vshost.exe (0x030C) 0x1390 SharePoint Foundation Monitoring b4ly High Leaving Monitored Scope (Event Receiver (Microsoft.SharePoint, Version=188.8.131.52, Culture=neutral, PublicKeyToken=71e9bce111e9429c, Microsoft.SharePoint.Workflow.SPWorkflowAutostartEventReceiver)). Execution Time=8071.44958367614
As you can see, the firing of the workflow start event and event receiver all happened in the console application’s process.
In addition, Visual Studio showed that the workflow template dll was indeed loaded in the console application’s memory:
Conclusion: When writing a console application or other short-lived process to add or change an item in a SharePoint list or document library, be aware that the automatically started workflow may not have a chance to start because the process it is supposed to be loaded into may have finished running too quickly. I am starting to wonder whether some of the event firing and event receivers in SharePoint follow a similar memory process.