我写了一个简单的线程同步程序。但是当我运行这个程序时,我得到一个错误“进程无法访问文件'D:\Vivek.txt',因为它正被另一个进程使用。” 为什么我收到此错误。
class Program
{
const string Filepath = "D:\\Vivek.txt";
static AutoResetEvent writerwaithandle= new AutoResetEvent(true);// Signaled state
static AutoResetEvent readerwaithandle = new AutoResetEvent(false);
static void Main()
{
if (File.Exists(Filepath))
{
File.Delete(Filepath);
}
File.CreateText(Filepath);
CreateWriterThread();
CreateReaderThread();
Console.ReadKey();
}
private static void CreateWriterThread()
{
for (int i = 1; i <= 10;i++ )
{
var thread = new Thread(WriteFile);
thread.Name = "Writer " + i;
thread.Start();
Thread.Sleep(250);
}
}
private static void CreateReaderThread()
{
for (int i = 1; i <= 10; i++)
{
var thread = new Thread(ReadFile);
thread.Name = "Reader " + i;
thread.Start();
}
}
private static void WriteFile()
{
writerwaithandle.WaitOne();
var stream = new FileStream(Filepath, FileMode.Append);
var streamwriter = new StreamWriter(stream);
streamwriter.WriteLine("written by"+Thread.CurrentThread.Name+DateTime.Now));
streamwriter.Flush();
streamwriter.Close();
readerwaithandle.Set();
}
private static void ReadFile()
{
readerwaithandle.WaitOne();
if (File.Exists(Filepath))
{
var stream = new FileStream(Filepath, FileMode.Open);
var streamreader = new StreamReader(stream);
var text = streamreader.ReadToEnd();
streamreader.Close();
Console.WriteLine("Read by thread {0} \n",Thread.CurrentThread.Name);
Console.WriteLine(text);
}
writerwaithandle.Set();
}
}
当我替换代码时
if (File.Exists(Filepath))
{
File.Delete(Filepath);
}
File.CreateText(Filepath);
至
if (!File.Exists(Filepath))
{
File.CreateText(Filepath);
}
该程序第一次显示相同的错误。之后它永远不会给出任何错误。请任何人告诉我错误区域,原因以及最好的解决方案。