Skip to main content

Simultaneously start multiple Sharepoint 2007 workflows using C# for a List

 Its known that we can start SharePoint 2007 workflows programmatically.  Here is the code that loops through all items in a list and starts the workflow for each item:

foreach(SPListItem item in list.Items)
{   
    SPListItem wrkItem =list.GetItemById(item.ID);   
    wrkflowmgr.StartWorkflow(wrkItem,wflassociation,
    wflassociation.AssociationData);
}

However the SharePoint Paradox here is that you can start only one workflow at a time , and have to wait for it to take its sweet time to finish, before you start the workflow for next item in list.  So what do you do if you have ( like i had ) a requirement to start a workflow on multiple items in a list simultaneously ?  Obviously you post a question shouting for help in stackoverflow. I was told:

there is no simultaneous method to start workflows for multiple list items at the same time.

But  i eventually figured out, that Multi Threading is the solution.

Steps

  • Create a Class “startWorkflow” that starts the workflow for a list item
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Workflow;
using Microsoft.SharePoint.Utilities;
using System.Threading;

namespace SimultaneousWorkflows
{
	class startWorkflow
	{
		int itemID;
        string siteURl;
        Guid gid; // GUID of the Workflow

        public startWorkflow(int iID, string sURl, Guid guidWfl)
        {
            itemID = iID;
            siteURl = sURl;
            gid = guidWfl;
        }
        public void startworkflowThread()
        {
           SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                 using (SPSite site = new SPSite(siteURl))
                    {
                        SPWeb web = site.RootWeb;
                        web.AllowUnsafeUpdates = true;
                        SPList list = web.Lists["Your List Name"];
                        SPWorkflowManager wrkflowmgr = site.WorkflowManager;
                        SPWorkflowAssociation wflassociation = list.WorkflowAssociations[gid];
                        SPListItem wrkItem = list.GetItemById(itemID);
                        wrkflowmgr.StartWorkflow(wrkItem, wflassociation, wflassociation.AssociationData);                                  
                    }   
            });                        
		}
	}
}

 

  • Implement Multithreading in the Timer Job Definition class file

I am just adding the relevant code here . Note: i was creating a timer job that would start the workflow , hence i updated the Timer Job Definition file , you can however do the following changes to the relevant class in your project.

Include the System.Collections.Generic and System.Threading namespaces.

 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Workflow;
using Microsoft.SharePoint.Utilities;
using System.Threading;
using System.Diagnostics;

Create a variable holding the GUID value of Workflow you want to start.

 public Guid wfguid = "The GUID value of Workflow you want to start" ;

Instantiate a Generic List ( Collection) of thread objects.

List<Thread> resThreadCollection = new List<Thread>();

Instantiate a Generic List ( Collection) of “startWorkflow” objects from the class you created above.

List<startWorkflow> startWorkFlowCollection = new List<startWorkflow>();

Update the Loop code as follows :

foreach(SPListItem item in list.Items)
{     
    startWorkflow thisItem = new startWorkflow(item.ID, siteUrl, wfguid);
    startWorkFlowCollection.Add(thisItem);
}

// Create a thread for each item added into startWorkFlowCollection
if (startWorkFlowCollection.Count > 0)
{
	foreach (startWorkflow itm in startWorkFlowCollection)
		{
			Thread MyThread = new Thread(new ThreadStart(itm.startworkflowThread));
			resThreadCollection.Add(MyThread);
		}
}

// Start the Threads	
 if (resThreadCollection.Count > 0)
{
	foreach (Thread tobeStarted in resThreadCollection)
		{
			tobeStarted.Start();
                }
} 

This is it , the workflows would start simultaneously now.

Comments

Popular posts from this blog

Telecom Churn Case Study Upgrad - Kaggle Competition - Godwin Paul Notebook

Telecom Churn Case Study Upgrad Telecom Churn Case Study ¶ Overview ¶ In the telecom industry, customers are able to choose from multiple service providers and actively switch from one operator to another. In this highly competitive market, the telecommunications industry experiences an average of 15-25% annual churn rate. Given the fact that it costs 5-10 times more to acquire a new customer than to retain an existing one, customer retention has now become even more important than customer acquisition. For many incumbent operators, retaining high profitable customers is the number one business goal. Business Objective ¶ The objective is to reduce customer churn and improve customer retention in a highly competitive market. Retaining high profitable customers is the number one business goal Case Study Objective ¶ The goal is to build a machine learning model using customer-level data to identify customers at high...

Llamhub SnowflakeReader: A Loader to query and chat Snowflake Data in your LLM Applications

  Snowflake Loader for LLM Recently my second contribution to Llamaindex "SnowflakeReader" was merged to Lllamahub repository. This loader connects to Snowflake (using SQLAlchemy under the hood). The user specifies a query and extracts Document objects corresponding to the results. This loader is designed to be used as a way to load data into  LlamaIndex  and/or subsequently used as a Tool in a  LangChain  Agent.  Usage Option 1: Pass your own SQLAlchemy Engine object of the database connection Here's an example usage of the SnowflakeReader. from llama_index import download_loader SnowflakeReader = download_loader ( 'SnowflakeReader' ) reader = SnowflakeReader ( engine = your_sqlalchemy_engine , ) query = "SELECT * FROM your_table" documents = reader . load_data ( query = query ) Option 2: Pass the required parameters to esstablish Snowflake connection Here's an example usage of the SnowflakeReader. from llama_index import down...

Happy Anniversary

Dec 2010, 6.15 PM, Thoraipakkam, Chennai Gavin alights from the shared auto, thinking to himself, "for gods sake its my first date ever and can I for once afford to have a non-creased t shirt travelling in this over cramped vehicle, great choice."   His mind shifts to the attire selection, "well this is my best , I wore this in Helsinki , Blue Levi Jeans , Black Puma T-Shirt albeit all purchased on discount from t-nagar sarvana stores. Are these fake ? I don’t want to know the answer," he thinks to himself. He looks down on his most dear possession his black fossil watch, time is 6.25. We have been meeting regularly in office, however this is the moment of truth. "Time to call Rachel buddy," he says to himself. As he reaches to his phone and the thought of calling Rachel races through his mind, his heart starts pounding at a speed he had felt only once - as a 6th grade student in military school when he had to jump and climb the 10 feet wall of the insu...