C# 고급 프로그래밍 21장 Page 470 [작업 및 병렬 프로그래밍] [취소]

취소

현재 다음 기술은 작업, 동시 컬렉션 클래스, 병렬 LINQ, 기타 중앙 집중식 동기화 메커니즘과 같은 표준 방식으로 장기 실행 작업 취소를 지원합니다.

취소는 협력적이며 강제되지 않습니다.

장기 실행 작업이 취소되었는지 확인하고 응답하여 제어를 반환합니다.

하나의 매개변수를 사용하여 취소를 지원하는 메서드입니다 CancellationToken.

  • 장기 실행 작업, 취소 방법 확인 :
    • IsCancellationRequested속성
    • 표시를 해제할 때 WaitHandle속성 을 사용하십시오.
    • Register다음 매개변수를 허용하는 메소드를 사용하십시오 .
      • Action: 표시가 없을 때 호출됨
      • ICancelableOperation, 이 인터페이스를 구현하는 객체의 메소드는 Cancel()취소 작업실 호출을 실행합니다.

Parallel.For() 취소

  • 병렬 옵션
    • 취소 토큰
      • CancellationTokenSource에 의해 생성됨
        • CancellationTokenSource는 ICancelableOperation 인터페이스를 구현합니다.
          • 따라서 CancellationToken을 사용하여 등록할 수 있고 Register() 메서드를 사용하여 작업을 취소할 때 정보를 등록할 수 있습니다.
            • Cancel() 메서드로 작업을 취소할 수 있습니다.
  • Parallel 클래스는 CancellationToken의 결과를 확인하고 작업을 취소합니다.
  • 작업이 취소되면 For()에서 OperationCanceledException이 발생합니다.
        public static void CancelParallelFor()
        {
            Console.WriteLine(nameof(CancelParallelFor));
            var cts = new CancellationTokenSource();
            cts.Token.Register(() => Console.WriteLine("*** token cancelled"));

            // send a cancel after 500 ms
            cts.CancelAfter(500);

            try
            {
                ParallelLoopResult result =
                  Parallel.For(0, 100, new ParallelOptions
                  {
                      CancellationToken = cts.Token,
                  },
                  x =>
                  {
                      Console.WriteLine($"loop {x} started");
                      int sum = 0;
                      for (int i = 0; i < 100; i++)
                      {
                          Task.Delay(2).Wait();
                          sum += i;
                      }
                      Console.WriteLine($"loop {x} finished");
                  });
            }
            catch (OperationCanceledException ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.WriteLine();
        }
复制代码

산출:

CancelParallelFor
loop 0 started
loop 24 started
loop 12 started
loop 36 started
loop 48 started
loop 60 started
loop 72 started
loop 84 started
loop 96 started
*** token cancelled
loop 24 finished
loop 84 finished
loop 0 finished
loop 36 finished
loop 96 finished
loop 12 finished
loop 48 finished
loop 72 finished
loop 60 finished
The operation was canceled.
复制代码

추천

출처juejin.im/post/7078292095940689933