private static readonly object wordCountCalculatorSyncObj = new object();
private static void ThreadDoWork() {
lock (wordCountCalculatorSyncObj) {
bool atLeastOneWordRemaining;
int thisWordIndex = currentWordIndex;
currentWordIndex = currentWordIndex + 1;
if (thisWordIndex >= wordList.Count) atLeastOneWordRemaining = false;
else atLeastOneWordRemaining = true;
while (atLeastOneWordRemaining) {
string thisWord = wordList[thisWordIndex];
bool firstOccurrenceOfWord = !wordCountDict.ContainsKey(thisWord);
if (curseWords.Contains(thisWord)) Console.WriteLine("Curse word detected!");
if (firstOccurrenceOfWord) wordCountDict.Add(thisWord, 1);
else wordCountDict[thisWord] = wordCountDict[thisWord] + 1;
thisWordIndex = currentWordIndex;
currentWordIndex = currentWordIndex + 1;
if (thisWordIndex >= wordList.Count) atLeastOneWordRemaining = false;
}
}
}
Code snippet taken from "Common Multithreading Mistakes in C# - I: Incorrect Granularity".