C# 多线程锁,写入文件防止被其他线程占用,ReaderWriterLockSlim 使用
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp4
{
class Program
{
static void Main(string[] args)
{
Writle();
Writle();
Writle();
Writle();
Writle();
}
static ReaderWriterLockSlim sucessLogWriteLockSlim = new ReaderWriterLockSlim();
static void Writle()
{
try
{
sucessLogWriteLockSlim.EnterWriteLock();
File.AppendAllText(@"D:\Sucess.txt", string.Format("{0}", DateTime.Now.ToString()));
}
catch
{
throw;
}
finally
{
sucessLogWriteLockSlim.ExitWriteLock();
}
}
}
}