
Writing Ecient Code in SharePoint
337
int currentIndex = 0;
for(int i = 0; i < numberOfThreads; i++){
//on the last iteration, ensure the number of items to insert is correct
if(i == numberOfThreads – 1){
itemsPerThread = stringsToInsert.Count – currentIndex;
}
//get the current range to be executed in this thread
List<string> range = stringsToInsert.GetRange(currentIndex, itemsPerThread);
//increment the index for use in the next iteration
currentIndex = currentIndex + itemsPerThread;
//start the thread
ThreadStart ts = new ThreadStart(delegate(){
BatchInsert(siteGuid, range);
});
Thread thread = new Thread(ts);
runningThreads.Add(thread);
Thread.Start();
}
//wait for all threads to complete processing
foreach(Thread thread in runningThreads){
thread.Join();
}
The preceding code snippet does not employ any sort of locking or thread synchronization beyond the
nal
Join() calls to ensure that all threads have completed execution before the code completes. The
Join() function pauses the current thread until the thread that the function is being called on com-
pletes. Although this example is simple, in the real world, multithreaded code can quickly become con-
voluted . For example, errors raised in a separate thread cannot be caught in other threads. Each thread
must have its own error handling logic, often with some mechanism to report errors back to the main
thread. Furthermore, you ...