为什么StreamWriter.Flush()在这里给出ObjectDisposedExeption?

时间:2018-12-17 18:47:26

标签: c# multithreading streamwriter

这是一个教育示例。尝试使

之类的output.txt
  

计数器+ 0

     

计数器+ 1

等通过用不同的线程写每一行。

using (StreamWriter output = File.CreateText("output.txt"))
{
    object block = new object();

    for (int i = 0; i < 10; i++)
    {
        Action<object> writeFunction = delegate (object obj) 
        {
            lock (block)
            {
                int counter = (int) obj;
                output.WriteLine("counter + " + counter);
                //output.Flush(); 
            }
        };

        Thread newThread = new Thread(new ParameterizedThreadStart(writeFunction));
        newThread.Start(i);
    }
}

注释的output.Flush()导致System.ObjectDisposedException“无法访问关闭的文件”。

0 个答案:

没有答案