Exemple #1
0
        /// <summary>
        /// 开启20个任务跑同一个对象,本来应该会得到40W这个数字,由于没有同步进行,几乎不会得到正确的输出值
        /// state1加了lock,会得到一个正确的值
        /// </summary>
        public static void RunTask()
        {
            int numTasks = 20;
            var state    = new SharedState();
            var state1   = new SharedState();
            var tasks    = new Task[numTasks];
            var tasks1   = new Task[numTasks];

            for (var i = 0; i < numTasks; i++)
            {
                tasks[i]  = Task.Run(() => { new Job(state).DoTheJob(); });
                tasks1[i] = Task.Run(() => new Job(state).DoThatJob());
            }
            Task.WaitAll(tasks);
            Task.WaitAll(tasks1);
            Console.WriteLine($"state summarized {state.State}");
            Console.WriteLine($"state1 summarized {state1.State}");
        }
Exemple #2
0
 public Job(SharedState sharedState)
 {
     _sharedState = sharedState;
 }