首页 新闻 搜索 专区 学院

简单的线程问题

0
[已解决问题] 解决于 2021-07-10 09:59
  static List<int> numberList = new List<int>();        

        static void Main(string[] args)
        {

            Thread thread1 = new Thread(() => Add(101,150));
            Thread thread2 = new Thread(() => Add(151,200));

            thread1.Start();
            thread2.Start();

            Thread.Sleep(1000);

            StringBuilder sb = new StringBuilder();
            foreach (var item in numberList)
            {
                sb.AppendFormat("\"{0}\",\r\n", item);
            }

            using (StreamWriter sw = new StreamWriter($"f:/{DateTime.Now.ToString("yyyyMMddHHmmsss")}.txt", false, Encoding.UTF8))
            {
                sw.Write(sb.ToString());
                sw.Flush();
                sw.Close();
                sw.Dispose();
            }

            Console.WriteLine("Hello World!");
            Console.ReadKey();
        }

        static void Add(int start,int end)
        {            
            Mutex mutex = new Mutex();
            if (mutex.WaitOne())
            {
                try
                {
                    for (int i = start; i <= end; i++)
                    {
                        numberList.Add(i);
                    }
                }
                finally
                {
                    mutex.ReleaseMutex();
                    mutex.Dispose();
                }
            }
        }

----------------------------
多运行几次会报错,或者输出的数字不对
parabeyond008的主页 parabeyond008 | 初学一级 | 园豆:2
提问于:2021-04-10 15:28
< >
分享
最佳答案
0

static void Add(int start,int end)
{
Mutex mutex = new Mutex(); // 这个mutex不应该在函数中建立, 需要全局的
if (mutex.WaitOne())

奖励园豆:5
蜗牛成成 | 菜鸟二级 |园豆:207 | 2021-04-10 22:15
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册