多线程方案中Guid.NewGuid()的重复值

问题描述 投票:0回答:1
class Program
    {
        private static string RequestID;
        static void Main(string[] args)
        {
            for (int i = 0; i < 1000; i++)
            {
                Thread t1 = new Thread(logs);
                Thread t2 = new Thread(logs);
                Thread t3 = new Thread(logs);
                t1.Start();
                t2.Start();
                t3.Start();
            }
            Console.ReadLine();
        }
        public static void logs()
        {
            RequestID = Guid.NewGuid().ToString();

            Console.WriteLine(RequestID);
        }
    }

根据我的分析,由于RequestID字段为static,因此会发生这种情况,但是我想在静态方法中使用此GuId。重复的ID是随机的,即,如果我在没有线程的情况下运行相同的代码,或者在少量迭代中运行Guid.NewGuid(),则没有重复的效果很好。

c# .net multithreading guid
1个回答
0
投票

您并没有完全得到重复,但是您的代码似乎有可能在生成GUID并将其写入控制台之间出现争用情况。

此行RequestID = Guid.NewGuid().ToString();在运行Console.WriteLine(RequestID);之前可能会在两个不同的线程中运行,导致控制台将两次输出最新的GUID(或多次),从而显得重复。

建议您锁定生成和打印的位置,以免出现竞争状况

 private static readonly Object obj = new Object();

 public static void logs()
 { 

    lock(obj){
        RequestID = Guid.NewGuid().ToString();

        Console.WriteLine(RequestID);
    }
 }
© www.soinside.com 2019 - 2024. All rights reserved.