Advertisement
Guest User

Untitled

a guest
Dec 18th, 2018
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.38 KB | None | 0 0
  1. internal static class CancellationDemo {
  2.    public static void Main() {
  3.       CancellationTokenSource cts = new CancellationTokenSource();
  4.  
  5.       // Передаем операции CancellationToken и число
  6.       ThreadPool.QueueUserWorkItem(=> Count(cts.Token1000)); 
  7.  
  8.       Console.WriteLine("Press <Enter> to cancel the operation.");
  9.       Console.ReadLine();
  10.       cts.Cancel();  // Если метод Count уже вернул управления, 
  11.                      // Cancel не оказывает никакого эффекта
  12.       // Cancel немедленно возвращает управление, метод продолжает работу...
  13.       Console.ReadLine();
  14.    }
  15.  
  16.    private static void Count(CancellationToken token, Int32 countTo) { 
  17.       for (Int32 count = 0; count <countTo; count++) {
  18.          if (token.IsCancellationRequested) {
  19.             Console.WriteLine("Count is cancelled");
  20.             break; // Выход их цикла для остановки операции
  21.          }
  22.  
  23.          Console.WriteLine(count);
  24.          Thread.Sleep(200);   // Для демонстрационных целей просто ждем
  25.       }
  26.       Console.WriteLine("Count is done");
  27.    }
  28. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement