Search code examples
c#replacerace-conditionparallel.foreach

Does C# Parallel.ForEach introduce a race condition when used to replace file text?


Does the following code block in C# introduce a race condition:

    Parallel.ForEach(guidDictionary, (dictionaryItem) =>
    {
        var fileName = dictionaryItem.Key;
        var fileText = File.ReadAllText(fileName, Encoding.ASCII);
        Parallel.ForEach(guidDictionary, (guidObj) =>
        {
            fileText = fileText.Replace(guidObj.Value.OldGuid, guidObj.Value.NewGuid);
        });

        File.WriteAllText(fileName, fileText);
    });

?


Solution

  • Yes, there is a race condition.

    fileText = fileText.Replace(guidObj.Value.OldGuid, guidObj.Value.NewGuid);
    

    If two separate threads start this operation, they both will start on the original string. Whichever one completes first will write to the fileText variable. When the second one completes, it will also write to the same variable. But since both threads are operating on the original string, when the second one completes the changes made by the first one will be overwritten.