Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using revision;
- public class Program
- {
- static async void Main(String[] args)
- {
- var cts = new CancellationTokenSource();
- Console.WriteLine("Main Thread Id " + Environment.CurrentManagedThreadId);
- var Task1 = ProcessBatch1(cts.Token);
- var Task2 = ProcessBatch2(cts.Token);
- // await Task.WhenAll(Task1, Task2);
- // await Task.WhenAny(Task1, Task2);
- Console.WriteLine("Enter Your Name:");
- var name = Console.ReadLine();
- Console.WriteLine($"Hello {name}");
- Console.ReadKey();
- }
- private static object _lock = new object();
- private static async Task ProcessBatch1(CancellationToken cancellationToken)
- {
- Console.WriteLine("Batch1 Thread Id " + Environment.CurrentManagedThreadId);
- await Task.Delay(1);
- Console.WriteLine("Batch1 (s2) Thread Id " + Environment.CurrentManagedThreadId);
- for (int i = 1; i <= 100; i++)
- {
- cancellationToken.ThrowIfCancellationRequested(); // the process decide the best time to break!
- lock (_lock)
- {
- Console.ForegroundColor = ConsoleColor.Red;
- Console.WriteLine(i);
- Console.ForegroundColor = ConsoleColor.White;
- }
- }
- }
- private static async Task ProcessBatch2(CancellationToken cancellationToken)
- {
- Console.WriteLine("Batch2 Thread Id " + Environment.CurrentManagedThreadId);
- await Task.Delay(1);
- Console.WriteLine("Batch2 (s2) Thread Id " + Environment.CurrentManagedThreadId);
- for (int i = 101; i <= 200; i++)
- {
- cancellationToken.ThrowIfCancellationRequested(); // the process decide the best time to break!
- lock (_lock)
- {
- Console.ForegroundColor = ConsoleColor.Green;
- Console.WriteLine(i);
- Console.ForegroundColor = ConsoleColor.White;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement