Partilhar via


Como: Ouvir os pedidos de cancelamento por sondagem

O exemplo a seguir mostra uma maneira pela qual o código do usuário pode sondar um token de cancelamento em intervalos regulares para ver se o cancelamento foi solicitado no thread de chamada. Este exemplo usa o System.Threading.Tasks.Task tipo, mas o mesmo padrão se aplica a operações assíncronas criadas diretamente pelo tipo ou pelo System.Threading.ThreadPoolSystem.Threading.Thread tipo.

Exemplo

A sondagem requer algum tipo de loop ou código recursivo que possa ler periodicamente o valor da propriedade booleana IsCancellationRequested . Se você estiver usando o System.Threading.Tasks.Task tipo e estiver aguardando a conclusão da tarefa no thread de chamada, poderá usar o ThrowIfCancellationRequested método para verificar a propriedade e lançar a exceção. Usando esse método, você garante que a exceção correta seja lançada em resposta a uma solicitação. Se você estiver usando um Task, então chamar esse método é melhor do que lançar manualmente um OperationCanceledException. Se você não tem que lançar a exceção, então você pode apenas verificar a propriedade e retornar do método se a propriedade é true.

using System;
using System.Threading;
using System.Threading.Tasks;

public struct Rectangle
{
   public int columns;
   public int rows;
}

class CancelByPolling
{
   static void Main()
   {
      var tokenSource = new CancellationTokenSource();
      // Toy object for demo purposes
      Rectangle rect = new Rectangle() { columns = 1000, rows = 500 };

      // Simple cancellation scenario #1. Calling thread does not wait
      // on the task to complete, and the user delegate simply returns
      // on cancellation request without throwing.
      Task.Run(() => NestedLoops(rect, tokenSource.Token), tokenSource.Token);

      // Simple cancellation scenario #2. Calling thread does not wait
      // on the task to complete, and the user delegate throws
      // OperationCanceledException to shut down task and transition its state.
      // Task.Run(() => PollByTimeSpan(tokenSource.Token), tokenSource.Token);

      Console.WriteLine("Press 'c' to cancel");
      if (Console.ReadKey(true).KeyChar == 'c') {
          tokenSource.Cancel();
          Console.WriteLine("Press any key to exit.");
      }

      Console.ReadKey();
      tokenSource.Dispose();
  }

   static void NestedLoops(Rectangle rect, CancellationToken token)
   {
      for (int col = 0; col < rect.columns && !token.IsCancellationRequested; col++) {
         // Assume that we know that the inner loop is very fast.
         // Therefore, polling once per column in the outer loop condition
         // is sufficient.
         for (int row = 0; row < rect.rows; row++) {
            // Simulating work.
            Thread.SpinWait(5_000);
            Console.Write("{0},{1} ", col, row);
         }
      }

      if (token.IsCancellationRequested) {
         // Cleanup or undo here if necessary...
         Console.WriteLine("\r\nOperation canceled");
         Console.WriteLine("Press any key to exit.");

         // If using Task:
         // token.ThrowIfCancellationRequested();
      }
   }
}
Imports System.Threading
Imports System.Threading.Tasks

Public Structure Rectangle
    Public columns As Integer
    Public rows As Integer
End Structure

Class CancelByPolling
    Shared Sub Main()
        Dim tokenSource As New CancellationTokenSource()
        ' Toy object for demo purposes
        Dim rect As New Rectangle()
        rect.columns = 1000
        rect.rows = 500

        ' Simple cancellation scenario #1. Calling thread does not wait
        ' on the task to complete, and the user delegate simply returns
        ' on cancellation request without throwing.
        Task.Run(Sub() NestedLoops(rect, tokenSource.Token), tokenSource.Token)

        ' Simple cancellation scenario #2. Calling thread does not wait
        ' on the task to complete, and the user delegate throws 
        ' OperationCanceledException to shut down task and transition its state.
        ' Task.Run(Sub() PollByTimeSpan(tokenSource.Token), tokenSource.Token)

        Console.WriteLine("Press 'c' to cancel")
        If Console.ReadKey(True).KeyChar = "c"c Then

            tokenSource.Cancel()
            Console.WriteLine("Press any key to exit.")
        End If

        Console.ReadKey()
        tokenSource.Dispose()
    End Sub

    Shared Sub NestedLoops(ByVal rect As Rectangle, ByVal token As CancellationToken)
        Dim col As Integer
        For col = 0 To rect.columns - 1
            ' Assume that we know that the inner loop is very fast.
            ' Therefore, polling once per column in the outer loop condition
            ' is sufficient.
            For col As Integer = 0 To rect.rows - 1
                ' Simulating work.
                Thread.SpinWait(5000)
                Console.Write("0',1' ", x, y)
            Next
        Next

        If token.IsCancellationRequested = True Then
            ' Cleanup or undo here if necessary...
            Console.WriteLine(vbCrLf + "Operation canceled")
            Console.WriteLine("Press any key to exit.")

            ' If using Task:
            ' token.ThrowIfCancellationRequested()
        End If
    End Sub
End Class

A chamada ThrowIfCancellationRequested é extremamente rápida e não introduz sobrecarga significativa nos loops.

Se você estiver ligando ThrowIfCancellationRequested, você só tem que verificar explicitamente a IsCancellationRequested propriedade se você tiver outro trabalho a fazer em resposta ao cancelamento além de jogar a exceção. Neste exemplo, você pode ver que o código realmente acessa a propriedade duas vezes: uma vez no acesso explícito e novamente no ThrowIfCancellationRequested método. Mas como o ato de ler a IsCancellationRequested propriedade envolve apenas uma instrução de leitura volátil por acesso, o acesso duplo não é significativo do ponto de vista do desempenho. Ainda é preferível chamar o método em vez de lançar manualmente o OperationCanceledException.

Consulte também