c#字典,Key是字符串,value是计数器.近似算法和线程安全

本文关键字:近似算法 线程 安全 计数器 字符串 字典 Key value | 更新日期: 2023-09-27 18:03:01

class Program
    {
        static Dictionary<string, int> Dictionary = new Dictionary<string, int>();
        static void Main(string[] args)
        {
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            Thread[] threads = new Thread[500];
            for(int i = 0; i < threads.Length; i++)
            {
                threads[i] = new Thread(InsertAlphabet);
                threads[i].Start();
            }
            for (int i = 0; i < threads.Length; i++)
            {
                threads[i].Join();
            }
            Console.WriteLine(Dictionary.Count);
            Console.WriteLine(stopwatch.ElapsedMilliseconds);
            foreach (KeyValuePair<string,int> kvp in Dictionary)
            {
                Console.WriteLine(kvp.Key + " " + kvp.Value);
            }
            stopwatch.Stop();
            Console.ReadLine();
        }
        private static void InsertAlphabet()
        {
            string[] alphabetArray = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
            foreach (var alphabet in alphabetArray)
            {
                Add(alphabet);
            }
        }
        public static void Add(string bar)
        {
            lock (Dictionary)
            {
                if (!Dictionary.ContainsKey(bar))
                {
                    Dictionary.Add(bar, 1);
                }
                else
                {
                    Dictionary[bar] += 1;
                }
            }
        }
    }

我已经创建了这个简单的控制台应用程序,以确保插入到字典中的数据是准确的。

对于同时尝试插入的500个线程,我将字母作为键和计数作为值插入的时间大约为3秒。

是否有一种方法可以通过涉及某种近似来提高性能(数据不需要100%准确)。允许准确率95%)。

还有关于如何改进字典中count的增量的建议。

c#字典,Key是字符串,value是计数器.近似算法和线程安全

我相信你可以使用AddOrUpdate的ConcurrentDictionary重载安全地完成这个任务,它接受一个委托来生成新的值。

委托接收当前值(如果有)。您可以提供将增量值添加到现有值的委托实现。如果还没有一个值,提供给AddOrUpdate的参数将被直接赋值为该键的值。

由于使用这个解决方案,ConcurrentDictionary内部锁定正在更新的键值,直到您的委托返回并更新内部值,因此多线程性能应该远远优于当前对整个字典结构的锁定。