private static void ThreadDoWorkSectioned(object threadStartParameter) {
ThreadWorkBlock localWorkBlock = (ThreadWorkBlock) threadStartParameter;
Dictionary<string, int> localWordCountDict = new Dictionary<string, int>();
int countPerSection = localWorkBlock.Count / NUM_SECTIONS_PER_THREAD;
for (int section = 0; section < NUM_SECTIONS_PER_THREAD; ++section) {
int startingIndex = localWorkBlock.StartingIndex + countPerSection * section;
int count = section < NUM_SECTIONS_PER_THREAD - 1 ? countPerSection : localWorkBlock.Count - countPerSection * (NUM_SECTIONS_PER_THREAD - 1);
localWordCountDict.Clear();
for (int i = startingIndex; i < startingIndex + count; ++i) {
string thisWord = wordList[i].ToUpper().Replace("-", String.Empty).Replace("'", String.Empty).Trim();
bool firstLocalOccurrenceOfWord = !localWordCountDict.ContainsKey(thisWord);
if (firstLocalOccurrenceOfWord) localWordCountDict.Add(thisWord, 1);
else localWordCountDict[thisWord] = localWordCountDict[thisWord] + 1;
}
lock (wordCountCalculatorSyncObj) {
foreach (var kvp in localWordCountDict) {
bool firstGlobalOccurrenceOfWord = !wordCountDict.ContainsKey(kvp.Key);
if (firstGlobalOccurrenceOfWord) wordCountDict.Add(kvp.Key, kvp.Value);
else wordCountDict[kvp.Key] += kvp.Value;
}
}
}
}
Code snippet taken from "Common Multithreading Mistakes in C# - II: Unnecessary Contention".