zoukankan      html  css  js  c++  java
  • C#使用读写锁解决多线程并发写入文件时线程同步的问题

    读写锁是以 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}
    ", 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}
    ", 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();
            }
        }

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

  • 相关阅读:
    About LabView
    Accuracy, Precision, Resolution & Sensitivity
    EIT: where is it now and what lies ahead?
    <2014 12 28> Some conclusions and thought recently
    <2014 10 01> 数学基础 Wikipedia
    关于HashMap
    elasticsearch index 之 put mapping
    elasticsearch index 之 create index(二)
    elasticsearch index 之 create index(-)
    elasticsearch index 之merge
  • 原文地址:https://www.cnblogs.com/xiaonangua/p/9413338.html
Copyright © 2011-2022 走看看