Advertisement
bero_0401

Task-Based Asynchronous Pattern

Oct 2nd, 2024 (edited)
33
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.03 KB | Source Code | 0 0
  1. using revision;
  2.  
  3. public class Program
  4. {
  5.  
  6.  
  7.     static async void Main(String[] args)
  8.     {
  9.  
  10.         var cts = new CancellationTokenSource();
  11.         Console.WriteLine("Main Thread Id " + Environment.CurrentManagedThreadId);
  12.         var Task1 = ProcessBatch1(cts.Token);
  13.         var Task2 = ProcessBatch2(cts.Token);
  14.  
  15.        //  await Task.WhenAll(Task1, Task2);
  16.  
  17.        // await Task.WhenAny(Task1, Task2);
  18.  
  19.         Console.WriteLine("Enter Your Name:");
  20.         var name = Console.ReadLine();
  21.         Console.WriteLine($"Hello {name}");
  22.         Console.ReadKey();
  23.  
  24.     }
  25.     private static object _lock = new object();
  26.  
  27.     private static async Task ProcessBatch1(CancellationToken cancellationToken)
  28.     {
  29.  
  30.         Console.WriteLine("Batch1 Thread Id " + Environment.CurrentManagedThreadId);
  31.         await Task.Delay(1);
  32.         Console.WriteLine("Batch1 (s2) Thread Id " + Environment.CurrentManagedThreadId);
  33.         for (int i = 1; i <= 100; i++)
  34.         {
  35.             cancellationToken.ThrowIfCancellationRequested(); // the process decide the best time to break!
  36.  
  37.             lock (_lock)
  38.             {
  39.                 Console.ForegroundColor = ConsoleColor.Red;
  40.                 Console.WriteLine(i);
  41.                 Console.ForegroundColor = ConsoleColor.White;
  42.             }
  43.         }
  44.     }
  45.     private static async Task ProcessBatch2(CancellationToken cancellationToken)
  46.     {
  47.  
  48.         Console.WriteLine("Batch2 Thread Id " + Environment.CurrentManagedThreadId);
  49.         await Task.Delay(1);
  50.         Console.WriteLine("Batch2 (s2) Thread Id " + Environment.CurrentManagedThreadId);
  51.         for (int i = 101; i <= 200; i++)
  52.         {
  53.             cancellationToken.ThrowIfCancellationRequested(); // the process decide the best time to break!
  54.                
  55.            
  56.             lock (_lock)
  57.             {
  58.                 Console.ForegroundColor = ConsoleColor.Green;
  59.                 Console.WriteLine(i);
  60.                 Console.ForegroundColor = ConsoleColor.White;
  61.             }
  62.         }
  63.     }
  64. }
  65.  
  66.  
  67.  
  68.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement