简体   繁体   English

在用于替换文件文本时,C#Parallel.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: C#中的以下代码块是否引入了竞争条件:

    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);
    });

?

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. 首先完成的fileText都会写入fileText变量。 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. 但是,由于两个线程都在原始字符串上运行,因此第二个线程完成时,第一个线程所做的更改将被覆盖。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM