Advertisement
bero_0401

Multithreading

Oct 2nd, 2024
25
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.27 KB | Source Code | 0 0
  1. using revision;
  2.  
  3. public class Program
  4. {
  5.  
  6.  
  7.     static void Main(String[] args){
  8.  
  9.         //var th1 = new Thread(ProcessBatch1);
  10.         //th1.Priority = ThreadPriority.Highest;
  11.         //var th2 = new Thread(ProcessBatch2);
  12.         //th2.Priority = ThreadPriority.Lowest;
  13.         //th1.IsBackground = true;
  14.         //th2.IsBackground = true;
  15.         //th1.Start();
  16.         //th2.Start();
  17.  
  18.         //var cts = new CancellationTokenSource();
  19.         //// threadPool make the thread BackGround
  20.         //ThreadPool.QueueUserWorkItem(ProcessBatch1 , cts.Token);
  21.         //ThreadPool.QueueUserWorkItem(ProcessBatch2 , cts.Token);
  22.         //Thread.Sleep(1200);
  23.         //cts.Cancel();
  24.        
  25.  
  26.     }
  27.     private static object _lock = new object(); // The Thread can not switched inside the lock block
  28.  
  29.     private static void ProcessBatch1(Object? state)
  30.     {
  31.         Thread.Sleep(1000);
  32.         for(int i =1; i<=1000;i++)
  33.         {
  34.             var cancellationToken = (CancellationToken)state;
  35.             if (cancellationToken.IsCancellationRequested) // the process decide the best time to break!
  36.                 return;
  37.             lock (_lock)
  38.             {
  39.                 Console.ForegroundColor = ConsoleColor.Red;
  40.                 Console.WriteLine(i);
  41.                 Console.ForegroundColor = ConsoleColor.White;
  42.             }
  43.         }
  44.     }
  45.     private static void ProcessBatch2(Object? state)
  46.     {
  47.         Thread.Sleep(1000);
  48.         for (int i = 1001; i <= 2000; i++)
  49.         {
  50.             var cancellationToken = (CancellationToken)state;
  51.             if (cancellationToken.IsCancellationRequested) // the process decide the best time to break!
  52.                 return;
  53.             lock (_lock)
  54.             {
  55.                 Console.ForegroundColor = ConsoleColor.Green;
  56.                 Console.WriteLine(i);
  57.                 Console.ForegroundColor = ConsoleColor.White;
  58.             }
  59.         }
  60.     }
  61. }
  62.  
  63. public class EventsTest
  64. {
  65.     public event CalculateEventHandler ExpressionCalculated;
  66.     public delegate void CalculateEventHandler(int x, int y);
  67.  
  68.     public int Calculate(int x, int y)
  69.     {
  70.         int result = x + y;
  71.         ExpressionCalculated?.Invoke(x, y);
  72.         Console.WriteLine(result);
  73.         return result;
  74.  
  75.     }
  76.  
  77. }
  78.  
  79.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement