zoukankan      html  css  js  c++  java
  • 通过锁字符串达到控制并发的效果C#

    lock锁的是地址

    而.net有内部机制使得相同的字符串内存地址是相同的(new string)除外

    下面上实验代码

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    
    namespace ConsoleApp5
    {
        class Program
        {
            static void Main(string[] args)
            {
                List<string> keyList = new List<string> { "key1","key2", "key1", "key1", "key1", "key1", };
    
                keyList.ForEach(u =>
                {
                    ThreadPool.QueueUserWorkItem(s =>
                    {
                        test.lockTestByString(u);
                    });
    
                });
    
                Console.Read();
            }
        }
        public class test {
    
            public static void lockTestByString(string key)
            {
                lock (key)
                {
                    Console.WriteLine("上锁2s key="+key);
                    Thread.Sleep(2000);
                    Console.WriteLine("解锁");
    
                }
            }
    
        }
    }
    

      运行

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    
    namespace ConsoleApp5
    {
        class Program
        {
            static void Main(string[] args)
            {
                List<string> keyList = new List<string> {new string('k',1), new string('k', 1), new string('k', 1), new string('k', 1) };
    
                keyList.ForEach(u =>
                {
                    ThreadPool.QueueUserWorkItem(s =>
                    {
                        test.lockTestByString(u);
                    });
    
                });
    
                Console.Read();
            }
        }
        public class test {
    
            public static void lockTestByString(string key)
            {
                lock (key)
                {
                    Console.WriteLine("上锁2s key="+key);
                    Thread.Sleep(2000);
                    Console.WriteLine("解锁");
    
                }
            }
    
        }
    }
    

      通过new字符串得出的运行结果

  • 相关阅读:
    移动端的爬坑路
    判断设备ios或android以及判断是否是微信内置浏览器
    使用vue directive 写好的滑动删除功能
    不用ajax,使用json数据渲染商品的方法
    vue中使用swiper的一些坑
    vue的自定义指令的坑
    better-score获取滑动距离的坑
    linux命令
    关于打印
    数据可视化
  • 原文地址:https://www.cnblogs.com/ProDoctor/p/7619847.html
Copyright © 2011-2022 走看看