首页 > Windows开发 > 详细

通过锁字符串达到控制并发的效果C#

时间:2018-04-24 10:06:27      阅读:195      评论:0      收藏:0      [点我收藏+]

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字符串得出的运行结果

技术分享图片

 

 转自:https://www.cnblogs.com/ProDoctor/p/7619847.html

 

通过锁字符串达到控制并发的效果C#

原文:https://www.cnblogs.com/hnsongbiao/p/8926086.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!