Пример #1
0
 public void PrintCollection(ThreadSafeCollection list)
 {
     lock (lockObject) {
         foreach (var item in list.List)
         {
             Console.WriteLine($"ThreadId: {Thread.CurrentThread.ManagedThreadId} print: {item}");
         }
         Thread.Sleep(200);
     }
 }
Пример #2
0
 public void AddRandomInts(ThreadSafeCollection list)
 {
     lock (lockObject) {
         for (int i = 0; i < 10; i++)
         {
             var value = rand.Next(minValue, maxValue);
             Console.WriteLine($"ThreadId: {Thread.CurrentThread.ManagedThreadId} adding: {value}");
             list.List.Add(value);
         }
         Thread.Sleep(20);
     }
 }
Пример #3
0
        static string RunTasks(int collectionLength, int threadCount)
        {
            var       list  = new ThreadSafeCollection(numberElements: collectionLength);
            Stopwatch watch = new Stopwatch();

            Task[] tasksList = new Task[threadCount];
            for (int i = 0; i < threadCount; i += 2)
            {
                tasksList[i]     = new Task(() => list.AddRandomInts(list));
                tasksList[i + 1] = new Task(() => list.PrintCollection(list));
            }

            watch.Start();
            Parallel.ForEach(tasksList, (t) => { t.Start(); });
            //foreach (var task in tasksList) {
            //    task.Start();
            //}
            Task.WaitAll(tasksList);
            watch.Stop();

            return($"Elapsed time for Tasks: {watch.ElapsedMilliseconds}");
        }