这是一个教育示例。尝试使
之类的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“无法访问关闭的文件”。