HOW TO:接聽多個取消要求

這個範例示範如何同時接聽兩個取消語彙基元,如此任一語彙基元要求取消作業時,您便可以取消作業。

注意事項注意事項

啟用 "Just My Code" 時,Visual Studio 有時候會在擲回例外狀況的程式碼行處中斷,並顯示「使用者程式碼未處理的例外狀況」之類的錯誤訊息。這是良性的錯誤。您可以按 F5 從中斷的地方繼續,並看到下面範例所示的例外處理行為。若要防止 Visual Studio 在遇到第一個錯誤時就中斷,只要取消選取 [工具]、[選項]、[偵錯]、[一般] 下的 [Just My Code] 核取方塊即可。

範例

在下列範例中,[M:M:System.Threading.CancellationTokenSource.CreateLinkedTokenSource(System.Threading.CancellationToken[])] 方法會用於將兩個語彙基元聯結成為一個。 這可以讓語彙基元傳遞給只接受一個取消語彙基元做為引數的方法。 這個範例示範常見的使用案例,其中方法必須觀察從類別外部傳入的語彙基元以及類別內部所產生的語彙基元。

Class LinkedTokenSourceDemo

    Shared Sub Main()

        Dim worker As New WorkerWithTimer()
        Dim cts As New CancellationTokenSource()

        ' Task for UI thread, so we can call Task.Wait wait on the main thread.
        Task.Factory.StartNew(Sub()

                                  Console.WriteLine("Press 'c' to cancel within 3 seconds after work begins.")
                                  Console.WriteLine("Or let the task time out by doing nothing.")
                                  If Console.ReadKey().KeyChar = "c"c Then
                                      cts.Cancel()
                                  End If
                              End Sub
    )
        ' Let the user read the UI message.
        Thread.Sleep(1000)

        ' Start the worker task.
        Dim t As Task = Task.Factory.StartNew(Sub() worker.DoWork(cts.Token), cts.Token)

        Try

            t.Wait()


        Catch ae As AggregateException

            For Each inner In ae.InnerExceptions
                Console.WriteLine(inner.Message)
            Next
        End Try

        Console.WriteLine("Press any key to exit.")
        Console.ReadKey()
    End Sub
End Class

Class WorkerWithTimer

    Dim internalTokenSource As CancellationTokenSource
    Dim token As CancellationToken
    Dim myTimer As Timer

    Public Sub WorkerWithTimer()

        internalTokenSource = New CancellationTokenSource()
        token = internalTokenSource.Token

        ' A toy cancellation trigger that times out after 3 seconds
        ' if the user does not press 'c'.
        myTimer = New Timer(New TimerCallback(AddressOf CancelAfterTimeout), Nothing, 3000, 3000)
    End Sub


    Public Sub DoWork(ByVal externalToken As CancellationToken)

        ' Create a new token that combines the internal and external tokens.
        Dim internalToken As CancellationToken = internalTokenSource.Token
        Dim linkedCts As CancellationTokenSource =
        CancellationTokenSource.CreateLinkedTokenSource(internalToken, externalToken)
        Using (linkedCts)
            Try
                DoWorkInternal(linkedCts.Token)

            Catch e As OperationCanceledException
                If e.CancellationToken = internalToken Then
                    Console.WriteLine("Operation timed out.")

                ElseIf e.CancellationToken = externalToken Then
                    Console.WriteLine("Canceled by external token.")
                    externalToken.ThrowIfCancellationRequested()
                End If

            End Try
        End Using
    End Sub


    Private Sub DoWorkInternal(ByVal token As CancellationToken)

        For i As Integer = 0 To 1000

            If token.IsCancellationRequested Then

                ' We need to dispose the timer if cancellation
                ' was requested by the external token.
                myTimer.Dispose()

                ' Output for demonstration purposes.
                Console.WriteLine("\r\nCancelling per request.")

                ' Throw the exception.
                token.ThrowIfCancellationRequested()
            End If

            ' Simulating work.
            Thread.SpinWait(7500000)
            Console.Write("working... ")
        Next
    End Sub

    Public Sub CancelAfterTimeout(ByVal state As Object)

        Console.WriteLine("\r\nTimer fired.")
        internalTokenSource.Cancel()
        myTimer.Dispose()
    End Sub
End Class
namespace WaitForMultiple
{
    using System;
    using System.Threading;
    using System.Threading.Tasks;

    class LinkedTokenSourceDemo
    {
        static void Main()
        {
            WorkerWithTimer worker = new WorkerWithTimer();
            CancellationTokenSource cts = new CancellationTokenSource();

            // Task for UI thread, so we can call Task.Wait wait on the main thread.
            Task.Factory.StartNew(() =>
            {
                Console.WriteLine("Press 'c' to cancel within 3 seconds after work begins.");
                Console.WriteLine("Or let the task time out by doing nothing.");
                if (Console.ReadKey().KeyChar == 'c')
                    cts.Cancel();
            });

            // Let the user read the UI message.
            Thread.Sleep(1000);

            // Start the worker task.
            Task task = Task.Factory.StartNew(() => worker.DoWork(cts.Token), cts.Token);


            try
            {
                task.Wait(cts.Token);
            }

            catch (OperationCanceledException e)
            {
                if (e.CancellationToken == cts.Token)
                    Console.WriteLine("Canceled from UI thread throwing OCE.");
            }


            catch (AggregateException ae)
            {
                Console.WriteLine("AggregateException caught: " + ae.InnerException);
                foreach (var inner in ae.InnerExceptions)
                {
                    Console.WriteLine(inner.Message + inner.Source);
                }
            }

            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }
    }

    class WorkerWithTimer
    {
        CancellationTokenSource internalTokenSource = new CancellationTokenSource();
        CancellationToken internalToken;
        CancellationToken externalToken;
        Timer timer;

        public WorkerWithTimer()
        {
            internalTokenSource = new CancellationTokenSource();
            internalToken = internalTokenSource.Token;

            // A toy cancellation trigger that times out after 3 seconds
            // if the user does not press 'c'.
            timer = new Timer(new TimerCallback(CancelAfterTimeout), null, 3000, 3000);
        }


        public void DoWork(CancellationToken externalToken)
        {
            // Create a new token that combines the internal and external tokens.
            this.internalToken = internalTokenSource.Token;
            this.externalToken = externalToken;

            using (CancellationTokenSource linkedCts =
                    CancellationTokenSource.CreateLinkedTokenSource(internalToken, externalToken))
            {
                try
                {
                    DoWorkInternal(linkedCts.Token);
                }
                catch (OperationCanceledException)
                {
                    if (internalToken.IsCancellationRequested)
                    {
                        Console.WriteLine("Operation timed out.");
                    }
                    else if (externalToken.IsCancellationRequested)
                    {
                        Console.WriteLine("Cancelling per user request.");
                        externalToken.ThrowIfCancellationRequested();
                    }
                }
            }
        }


        private void DoWorkInternal(CancellationToken token)
        {
            for (int i = 0; i < 1000; i++)
            {
                if (token.IsCancellationRequested)
                {
                    // We need to dispose the timer if cancellation
                    // was requested by the external token.
                    timer.Dispose();

                    // Throw the exception.
                    token.ThrowIfCancellationRequested();
                }

                 // Simulating work.
                Thread.SpinWait(7500000);
                Console.Write("working... ");
            }
        }

        public void CancelAfterTimeout(object state)
        {
            Console.WriteLine("\r\nTimer fired.");
            internalTokenSource.Cancel();
            timer.Dispose();
        }
    }
}

當連結後的語彙基元擲回 OperationCanceledException 時,傳遞給例外狀況的語彙基元為連結後的語彙基元,而不是前置項語彙基元。 若要判斷取消的是哪個語彙基元,請直接檢查前置項語彙基元的狀態。

在這個範例中,絕對不可擲回 AggregateException,但在此處卻攔截到,原因是在現實情況中,除了 OperationCanceledException 以外,從工作委派中擲回的任何其他例外狀況,都是包裝在 OperationCanceledException

請參閱

概念

取消