(精华)2020年12月23日 .NET Core 多线程底层详解(读写锁)

ReaderWriterLock 定义支持单个写线程和多个读线程的锁。该锁的作用主要是解决并发读的性能问题,使用该锁,可以大大提高数据并发访问的性能,只有在写时,才会阻塞所有的读锁。

using System.Collections.Generic;
using System.Windows;
using System.Threading;


namespace FYSTest
{
    public partial class MainWindow : Window
    {
        List<int> list = new List<int>();
        private ReaderWriterLock _rwlock = new ReaderWriterLock();

        public MainWindow()
        {
            InitializeComponent();
            Thread ThRead = new Thread(new ThreadStart(Read));
            ThRead.IsBackground = true;
            Thread ThRead2 = new Thread(new ThreadStart(Read));
            ThRead2.IsBackground = true;
            Thread ThWrite = new Thread(new ThreadStart(Write));
            ThWrite.IsBackground = true;
            ThRead.Start();
            ThRead2.Start();
            ThWrite.Start();
        }

        private void Read()
        {
            while (true)
            {
                //使用一个 System.Int32 超时值获取读线程锁。
                _rwlock.AcquireReaderLock(100);
                try
                {
                    if (list.Count > 0)
                    {
                        int result = list[list.Count - 1];
                    }
                }
                finally
                {
                    //减少锁计数,释放锁
                    _rwlock.ReleaseReaderLock();
                }
            }
        }

        int WriteCount = 0;//写次数
        private void Write()
        {
            while (true)
            {
                //使用一个 System.Int32 超时值获取写线程锁。
                _rwlock.AcquireWriterLock(100);
                try
                {
                    list.Add(WriteCount++);
                }
                finally
                {
                    //减少写线程锁上的锁计数,释放写锁
                    _rwlock.ReleaseWriterLock();
                }
            }
        }
    }
}
public static class ReaderWriterLockSample
{
    //读写锁,当资源处于写入模式时,其他线程写入需要等待本次写入结束之后才能继续写入
    private static readonly ReaderWriterLockSlim Lock = new ReaderWriterLockSlim();

    private const string FilePath = "log.txt";
    private const int LogCount = 100;
    private static int _writedCount;
    private static int _failedCount;

    private static void WriteLog()
    {
        // 获取写入锁
        Lock.EnterWriteLock();
        try
        {
            var now = DateTime.Now;
            var logContent =
                $"ThreadId={Thread.CurrentThread.ManagedThreadId},{now.ToLongTimeString()}\r\n";

            File.AppendAllText(FilePath, logContent);
            _writedCount++;
        }
        catch (Exception)
        {
            _failedCount++;
        }
        finally
        {
            // 释放写入锁
            Lock.ExitWriteLock();
        }
    }


    public static void Run()
    {
        // 并行执行,等待执行结果
        Parallel.For(0, LogCount, e =>
        {
            WriteLog();
        });

        Console.WriteLine($"Write Count:{_writedCount};Failed Count:{_failedCount}");
        Console.Read();
    }
}
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 猿与汪的秘密 设计师:上身试试 返回首页