棒!读写文件流加锁示例,但是不知道怎么管时序
作者:互联网
` private static ReaderWriterLockSlim _rwl = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);//暂时不知道和下面的有啥区别
private void Form1_Load(object sender, EventArgs e)
{
Thread thread1 = new Thread(() =>
{
while (true)
{
SaveCSV("a", "E:\\Project.csv");
}
});
Thread thread2 = new Thread(() =>
{
while (true)
{
SaveCSV("b", "E:\\Project.csv");
}
});
thread1.Start();
thread2.Start();
}
static ReaderWriterLockSlim LogWriteLock = new ReaderWriterLockSlim();
public void SaveCSV(String Columns, String fileName)
{
try
{
LogWriteLock.EnterWriteLock();//加锁
if (!File.Exists(fileName))
{
using (FileStream fs = new FileStream(fileName, System.IO.FileMode.CreateNew))
{
using (StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default))
{
sw.WriteLine("NG模组码,托盘码,NG代码"); //写入硬盘
sw.NewLine = Environment.NewLine;
}
}
}
else
{
using (FileStream fs = new FileStream(fileName, System.IO.FileMode.Append))
{
using (StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default))
{
sw.WriteLine(Columns); //写入硬盘
sw.NewLine = Environment.NewLine;
}
}
}
}
catch (Exception ex)
{
}
finally
{//解锁
LogWriteLock.ExitWriteLock();
}
}`
标签:加锁,示例,FileStream,读写,NewLine,sw,System,new,ReaderWriterLockSlim 来源: https://www.cnblogs.com/dengzhekaihua/p/16217524.html