Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using revision;
- public class Program
- {
- static void Main(String[] args){
- //var th1 = new Thread(ProcessBatch1);
- //th1.Priority = ThreadPriority.Highest;
- //var th2 = new Thread(ProcessBatch2);
- //th2.Priority = ThreadPriority.Lowest;
- //th1.IsBackground = true;
- //th2.IsBackground = true;
- //th1.Start();
- //th2.Start();
- //var cts = new CancellationTokenSource();
- //// threadPool make the thread BackGround
- //ThreadPool.QueueUserWorkItem(ProcessBatch1 , cts.Token);
- //ThreadPool.QueueUserWorkItem(ProcessBatch2 , cts.Token);
- //Thread.Sleep(1200);
- //cts.Cancel();
- }
- private static object _lock = new object(); // The Thread can not switched inside the lock block
- private static void ProcessBatch1(Object? state)
- {
- Thread.Sleep(1000);
- for(int i =1; i<=1000;i++)
- {
- var cancellationToken = (CancellationToken)state;
- if (cancellationToken.IsCancellationRequested) // the process decide the best time to break!
- return;
- lock (_lock)
- {
- Console.ForegroundColor = ConsoleColor.Red;
- Console.WriteLine(i);
- Console.ForegroundColor = ConsoleColor.White;
- }
- }
- }
- private static void ProcessBatch2(Object? state)
- {
- Thread.Sleep(1000);
- for (int i = 1001; i <= 2000; i++)
- {
- var cancellationToken = (CancellationToken)state;
- if (cancellationToken.IsCancellationRequested) // the process decide the best time to break!
- return;
- lock (_lock)
- {
- Console.ForegroundColor = ConsoleColor.Green;
- Console.WriteLine(i);
- Console.ForegroundColor = ConsoleColor.White;
- }
- }
- }
- }
- public class EventsTest
- {
- public event CalculateEventHandler ExpressionCalculated;
- public delegate void CalculateEventHandler(int x, int y);
- public int Calculate(int x, int y)
- {
- int result = x + y;
- ExpressionCalculated?.Invoke(x, y);
- Console.WriteLine(result);
- return result;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement