标签:void 导致 bsp line stat content cep exception 结果
读写锁是以 ReaderWriterLockSlim 对象作为锁管理资源的,不同的 ReaderWriterLockSlim 对象中锁定同一个文件也会被视为不同的锁进行管理,这种差异可能会再次导致文件的并发写入问题,所以 ReaderWriterLockSlim 应尽量定义为只读的静态对象。
多线程同时写入文件
class Program { static int writeCount = 0; static int wrongCount = 0; static void Main(string[] args) { Test(); } static void Test() { //迭代运行写入内容,由于多个线程同时写入同一个文件将会导致错误 Parallel.For(0, 100, e => { try { writeCount++; var logFilePath = "/test.txt"; var now = DateTime.Now; var logContent = string.Format("Tid: {0}{1} {2}=>{3}\r\n", Thread.CurrentThread.ManagedThreadId.ToString().PadRight(4), now.ToLongDateString(), now.ToLongTimeString(), writeCount); File.AppendAllText(logFilePath, logContent); } catch (Exception ex) { wrongCount++; Console.WriteLine("累计失败" + wrongCount + "次"); Console.WriteLine(ex.Message); throw; } }); Console.Read(); } }
运行结果
只有部分数据写入了文件
多线程使用读写锁同步写入文件
class Program { static int writeCount = 0; static int wrongCount = 0; static void Main(string[] args) { Test(); } static ReaderWriterLockSlim writeLock = new ReaderWriterLockSlim(); static void Test() { //迭代运行写入内容 Parallel.For(0, 100, e => { try { writeLock.EnterWriteLock(); writeCount++; var logFilePath = "/test.txt"; var now = DateTime.Now; var logContent = string.Format("Tid: {0}{1} {2}=>{3}\r\n", Thread.CurrentThread.ManagedThreadId.ToString().PadRight(4), now.ToLongDateString(), now.ToLongTimeString(), writeCount); File.AppendAllText(logFilePath, logContent); } catch (Exception ex) { wrongCount++; Console.WriteLine("累计失败" + wrongCount + "次"); Console.WriteLine(ex.Message); throw; } finally { writeLock.ExitWriteLock(); } }); Console.Read(); } }
运行成功,数据全部写入文件
标签:void 导致 bsp line stat content cep exception 结果
原文地址:https://www.cnblogs.com/xiaonangua/p/9413338.html