当多个线程写入同一个文件时会发生什么负面影响?

O.O*_*O.O 0 .net c# multithreading integration-testing .net-2.0

以下是失败的集成测试的伪代码:

[测试]

void TestLogger()
    // Init static logger
    Logger.Init(pathToFile);

    // Create five threads that will call LogMessages delegate
    for i = 1 to 5 
    {
       Thread aThread = new Thread(LogMessages)
       aThread.Start(i);
    }

    // let threads complete their work
    Thread.Sleep(30000);

    /// read from log file and count the lines
    int lineCount = GetLineCount();

    // 5 threads, each logs 5 times = 25 lines in the log
    Assert.Equal(25, lineCount);


static void LogMessages( object data )
  // each thread will log five messages
  for i = 1 to 5 
  Logger.LogMessage(i.ToString() + " " + DateTime.Now.Ticks.ToString());
  Thread.Sleep(50);
Run Code Online (Sandbox Code Playgroud)

每次运行测试时,行数似乎都会发生变化.有时行数为23,有时为25.

在我仔细挖掘代码之后,我注意到多个线程同时访问了日志文件(通过滴答计数验证相同).对此文件的访问没有锁定,但同时我看不到抛出任何异常.任何人都可以解释为什么运行之间的日志行数不一致?此外,这是多个线程同时写入同一文件的负面影响吗?

And*_*ber 5

正如你所拥有的那样,竞争条件众所周知是不可预测的.你永远不知道有多少写不能正常工作 - 有时甚至可能完全正常.是的,这是在没有同步的情况下从多个线程写入同一文件的负面影响.