Best way to run multiple workflows simultaneously in WF 4.0

I have a routine that creates n instances of a specific workflow and starts them one at a time. How could I fire them asynchronously?

Current p-code:

forloop

// Create var syncEvent = new AutoResetEvent (false); WorkflowInstance myInstance = new WorkflowInstance (new SomeWorkflow (), parameters);

// Events // Completed myInstance.OnCompleted = delegate(WorkflowCompletedEventArgs e) { syncEvent.Set(); }; // Unhandled Exception myInstance.OnUnhandledException = delegate(WorkflowUnhandledExceptionEventArgs e) { // Message Console.WriteLine(e.UnhandledException.ToString()); return UnhandledExceptionAction.Terminate; }; // Aborted myInstance.OnAborted = delegate(WorkflowAbortedEventArgs e) { // Message Console.WriteLine(e.Reason); syncEvent.Set(); }; // Run myInstance.Run(); // Wait syncEvent.WaitOne(); 
+4
source share
3 answers

I think the easiest way to get from here to this is to simply create some wait descriptors and end with WaitAll (). Not the smartest solution, but it will work for you. BTW, I would recommend using a real class that contains a reference to the associated wait descriptor and avoiding anon methods.

  List<ManualResetEvent> items = new List<ManualResetEvent>(); foreach (Type job in queue) { WorkflowInstance myInstance = new WorkflowInstance(job, parameters); ManualResetEvent syncEvent = new ManualResetEvent(false); items.Add(syncEvent); // Completed myInstance.OnCompleted = delegate(WorkflowCompletedEventArgs e) { syncEvent.Set(); }; // Unhandled Exception myInstance.OnUnhandledException = delegate(WorkflowUnhandledExceptionEventArgs e) { // Message Console.WriteLine(e.UnhandledException.ToString()); return UnhandledExceptionAction.Terminate; }; // Aborted myInstance.OnAborted = delegate(WorkflowAbortedEventArgs e) { // Message Console.WriteLine(e.Reason); syncEvent.Set(); }; // Run myInstance.Run(); } // Wait WaitHandle.WaitAll(items.ToArray()); 
+4
source

Using a parallel structure, it will be easier.

+1
source

Do you really need them to work on separate threads? I think, since you are already using Workflow, this should be the easiest way to solve the problem, using a workflow to "organize your work."

 { var ArgsToProcess = new List<string> { "arg_one", "arg_two", "arg_three" }; var delegateArg = new DelegateInArgument<string> { Name = "s" }; Activity toRun = new ParallelForEach<string> { Body = new ActivityAction<string> { Argument = delegateArg, Handler = new Workflow1() //Plug your workflow here { Arg = delegateArg } } }; WorkflowInvoker.Invoke(toRun, new Dictionary<string, object> { {"Values", ArgsToProcess} }); } 
0
source

All Articles