码迷,mamicode.com
首页 > 编程语言 > 详细

C#使用读写锁解决多线程并发写入文件时线程同步的问题

时间:2018-08-03 14:34:32      阅读:366      评论:0      收藏:0      [点我收藏+]

标签: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();
        }
    }

运行成功,数据全部写入文件

技术分享图片

 

C#使用读写锁解决多线程并发写入文件时线程同步的问题

标签:void   导致   bsp   line   stat   content   cep   exception   结果   

原文地址:https://www.cnblogs.com/xiaonangua/p/9413338.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!