Exemplo n.º 1
0
 static void Work(Canceler c)
 {
     while (true)
     {
         c.ThrowIfCancellationRequested();
         // ...
         try
         {
             OtherMethod(c);
         }
         finally { /* any required cleanup */ }
     }
 }
Exemplo n.º 2
0
        /*
         *
         * var cancelSource = new CancellationTokenSource();
         * new Thread (() => Work (cancelSource.Token)).Start();
         * void Work (CancellationToken cancelToken)
         *  {
         *  cancelToken.ThrowIfCancellationRequested();
         *  ...
         *  }
         */

        public static void Caller()
        {
            var canceler = new Canceler();

            new Thread(() =>
            {
                try
                {
                    Work(canceler);
                }
                catch (OperationCanceledException)
                {
                    Console.WriteLine("Canceled");
                }
            }).Start();
            Thread.Sleep(1000);
            canceler.Cancel();
        }
Exemplo n.º 3
0
 static void OtherMethod(Canceler c)
 {
     // Do some thing...
     c.ThrowIfCancellationRequested();
 }