title: How to use the CancellationToken property?
body: <p>Compared to the preceding code <a href="http://www.albahari.com/threading/part3.aspx#_Safe_Cancellation" rel="noreferrer">for class RulyCanceler</a>, I wanted to run code using  <code>CancellationTokenSource</code>.</p>
  
  <p>How do I use it as mentioned in <a href="http://www.albahari.com/threading/part3.aspx#_Cancellation_Tokens" rel="noreferrer">Cancellation Tokens</a>, i.e. without throwing/catching an exception?   Can I use the <code>IsCancellationRequested</code> property?  </p>
  
  <p>I attempted to use it like this:  </p>
  
  <pre><code>cancelToken.ThrowIfCancellationRequested();
  </code></pre>
  
  <p>and</p>
  
  <pre><code>try
  {
    new Thread(() =&gt; Work(cancelSource.Token)).Start();
  }
  catch (OperationCanceledException)
  {
    Console.WriteLine("Canceled!");
  }
  </code></pre>
  
  <p>but this gave a run-time error on <code>cancelToken.ThrowIfCancellationRequested();</code> in method <code>Work(CancellationToken cancelToken)</code>:  </p>
  
  <pre><code>System.OperationCanceledException was unhandled
    Message=The operation was canceled.
    Source=mscorlib
    StackTrace:
         at System.Threading.CancellationToken.ThrowIfCancellationRequested()
         at _7CancellationTokens.Token.Work(CancellationToken cancelToken) in C:\xxx\Token.cs:line 33
         at _7CancellationTokens.Token.&lt;&gt;c__DisplayClass1.&lt;Main&gt;b__0() in C:\xxx\Token.cs:line 22
         at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
         at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
         at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
         at System.Threading.ThreadHelper.ThreadStart()
    InnerException:
  </code></pre>
  
  <p>The code that I successfully ran caught the OperationCanceledException in the new thread:</p>
  
  <pre><code>using System;
  using System.Threading;
  namespace _7CancellationTokens
  {
    internal class Token
    {
      private static void Main()
      {
        var cancelSource = new CancellationTokenSource();
        new Thread(() =&gt;
        {
           try
           {
             Work(cancelSource.Token); //).Start();
           }
           catch (OperationCanceledException)
           {
              Console.WriteLine("Canceled!");
           }
           }).Start();
  
        Thread.Sleep(1000);
        cancelSource.Cancel(); // Safely cancel worker.
        Console.ReadLine();
      }
      private static void Work(CancellationToken cancelToken)
      {
        while (true)
        {
          Console.Write("345");
          cancelToken.ThrowIfCancellationRequested();
        }
      }
    }
  }
  </code></pre>