Peak_Tsui 2018-10-24 04:13 采纳率: 0%
浏览 737

大神帮看下代码,为什么ManualResetEventSlim 没有锁住线程

List中的N为什么会有重复?这是Framework中的bug吗?(我的电脑4核i5 7500)

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp
{
    class Program
    {
        //static AutoResetEvent mre = new AutoResetEvent(true);
        static ManualResetEventSlim mre = new ManualResetEventSlim(true);
        static List<string> list = new List<string>();
        static void Main(string[] args)
        {

            Task[] tasks = new Task[10000];
            for (int i = 0; i < 10000; i++)
            {
                tasks[i] = Task.Factory.StartNew(Test);
                //tasks[i].ContinueWith(t => Set());
            }

            Task.WaitAll(tasks);

            var q = from t in list
                    group t by t into g
                    where g.Count() >1
                    select new
                    {
                        g.Key,
                        Count = g.Count()
                    };

            q.ToList().ForEach((t) => Console.WriteLine(t.Key + "---" + t.Count));

            Console.WriteLine("OK");
        }

        //static void Set()
        //{
        //    mre.Set();
        //}

        static int n = 0;
        static string Test()
        {
            try
            {
                mre.Wait();
                mre.Reset();
                Interlocked.Increment(ref n);
                var s = n.ToString();
                list.Add(s);
                return s;
            }
            finally
            {
                mre.Set();
            }
        }

    }
}

  • 写回答

1条回答 默认 最新

  • dabocaiqq 2018-10-26 07:00
    关注
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作