Thread Safety in ManualWorkflowSchedulerService.RunWorkflow
No, I do not think so. The following is a related excerpt from the book 'Essential Windows Workflow Foundation'
Although operations with WorkflowInstance can be invoked by arbitrary threads, the WF scheduler, hosted within a program instance, is served by a single thread. The WF runtime ensures that no other thread can interfere with or service the scheduler while its dispatch loop is actively processing work items. To be clear, a hosting application can call the WorkflowInstance on methods on separate threads at the same time - this does not affect the scheduler for executing activities on a dedicated thread (for a sequence of execution).
EDIT: To further explore the issue, I created a wf with ParallelActivity
which contains two steps HandleExternalEvent
. The handler for invoked
each action simply makes its thread sleep for 3 seconds. In the host program, I created two threads and triggered two events through the service. Also, I will subclass ManualWorkflowSchedulerService
to keep track of its method Schedule
. Here are the results (time in 10ms):
Src Time Thread
HOST 7616 1 CreateWorkflow
MWSS 7642 1 Schedule workflow
HOST 8297 12 Trigger event 1 and wait for RunWorkflow
MWSS 8316 12 Schedule workflow
WF 8327 12 Handler 1 Invoked...wait 3 sec
HOST 8327 1 Press any key to exit...
HOST 8767 13 Trigger event 2 and wait for RunWorkflow
MWSS 8784 13 Schedule workflow
WF 38319 12 Handler 1 Completed
WF 38406 12 Handler 2 Invoked...wait 3 sec
WF 68396 12 Handler 2 Completed
HOST 68573 13 RunWorkflow for event 2 completed in 5,98 sec
HOST 68794 12 WorkflowCompleted
HOST 68795 12 RunWorkflow for event 1 completed in 6,05 sec
Some notes:
- The scheduler always uses the host thread to schedule the work item.
- A workflow instance does not always use the host thread to perform actions. If another activity is already in progress on a thread, that thread is used to perform all scheduled activities.
- The execution of the handlers is thread safe, but both threads wait for both handlers to finish!
If the latter bothers you, I would suggest the following posts:
- Understanding ParallelActivity in a Windows Workflow
- Use Workflow to invoke web services in parallel
By the way, can you share some information about the scenario you are facing?
source to share