I saw many articles which says microsoft.sharepoint.dll is not thread safe.
But when I run below code via 10 to 20 parallel threads it doesn't throw any error.
Although when I tried to multi thread foreach loop within SingleThread() which is defined below. It start throwing error at "SPListItemCollection" level.
//Main method:
ParallelOptions myOptons = new ParallelOptions { MaxDegreeOfParallelism = 10 };
int[] loop = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
Parallel.ForEach(loop, myOptons, myloop =>
{
SingleThread();
});
//Other method.
public void SingleThread()
{
DateTime startdate = DateTime.Now;
try
{
int count = 0;
SPWebService service = farm.Services.GetValue<SPWebService>("");
SPWebServiceCollection webServices = new SPWebServiceCollection(farm);
foreach (SPWebService webService in webServices) //Traverse Web Services
{
foreach (SPWebApplication webApp in webService.WebApplications)
{
string webApplicationUrl = webApp.GetResponseUri(SPUrlZone.Default).ToString();
SPSecurity.RunWithElevatedPrivileges(delegate ()
{
SPWebApplication webApplication = SPWebApplication.Lookup(new Uri(webApplicationUrl));
foreach (SPSite sps in webApplication.Sites)
{
if (sps != null)
{
string spSiteUrl = sps.RootWeb.Url;
//Console.WriteLine(spSiteUrl);
SPWeb oWebsite = (new SPSite(spSiteUrl).OpenWeb());
SPWebCollection collWebsite = oWebsite.Webs;
foreach (SPWeb web in collWebsite)
{
if (web != null)
{
foreach (SPList list in web.Lists)
{
if (list.BaseTemplate.ToString() == "DocumentLibrary")
{
//Error in below line when I tried to multi thread SPListItemCollection.
SPListItemCollection lstitemcoll = list.GetItems();
foreach (SPListItem lstitem in lstitemcoll)
{
count++;
}
}
}
}
}
}
}
});
}
}
DateTime enddate = DateTime.Now;
Console.WriteLine("Single Thread Count : {0}. Completed in {1} Seconds", count, (enddate - startdate).TotalSeconds);
}
catch (Exception ex)
{
string message = ex.Message;
}
}