C#:FileStream.ReadByte() 是多线程友好函数吗?

C#: is FileStream.ReadByte() a multi-threading friendly function?

所以我有 16 个线程同时 运行 这个方法:

    private void Work()
    {
        int currentByte;
        char currentChar;

        try
        {
            while (true)
            {
                position++;
                currentByte = file.ReadByte();
                currentChar = Convert.ToChar(currentByte);

                entries.Add(new Entry(currentChar));
            }
        }
        catch (Exception) { }
    }

然后我还有一个线程 运行使用这个方法:

    private void ManageThreads()
    {
        bool done;

        for(; ; )
        {
            done = !threads.Any(x => x.IsAlive == true);//Check if each thread is dead before continuing
            if (done)
                break;
            else
                Thread.Sleep(100);
        }
        PrintData();
    }

问题在于:PrintData 方法只是将 'entries' 列表中的所有内容打印到文本文件中。即使使用相同的输入文件,每次程序 运行 时此文本文件都是不同的。在谈到多线程应用程序时,我有点菜鸟,所以请随意提出批评。

通常,除非类型在其文档中明确调用线程安全,否则您应该假设它不是线程安全的*。 .Net 中的流没有这样的部分,应该被视为非线程安全的 - 使用适当的同步(即锁)来保证每次从一个线程访问每个流。

对于文件流还有另一个问题 - OS 级文件对象可能会从其他线程更新 - FileStream 试图通过检查其内部状态是否与 OS 状态匹配来缓解它- 请参阅 MSDN 上的 FileStream:remarks 部分。

如果你想要线程安全流,你可以尝试使用Synchronized方法,如C#, is there such a thing as a "thread-safe" stream?所示。

请注意,无论流是否线程安全,post 中的代码都会产生随机结果。流的线程安全只会保证所有字节都出现在输出中。如果使用非线程安全流,则根本没有任何保证,并且某些字节可能会出现多次,某些字节可能会被跳过,并且任何其他行为(崩溃、部分读取...)都是可能的。


* 与 "internal state of the instance will be consistent whether it is called from one thread or multiple" 中一样线程安全。 并不意味着从不同线程调用任意方法会导致有用的行为。