title: C# Throw OperationCanceledException from inside CancellationToken.Register
body: <p>I have a long running operation that I want to cancel after, say 5 secs.  Unfortunately, polling for IsCancellationRequested is not possible (long story).</p>
  
  <p>I used the code below to throw an OperationCanceledException inside the cancellation callback. I wanted to catch the exception in the main thread and handle it so that I can exit the application completely.  </p>
  
  <p>This doesn't seem to work properly as this results in an unhandled exception and the application doesn't terminate gracefully.</p>
  
  <p>Any help is appreciated.  Thanks!</p>
  
  <pre><code>    void TestTimeOut()
      {
          var cts = new CancellationTokenSource();
          cts.CancelAfter(5000);
  
          try
          {
              var task = Task.Run(() =&gt; LongRunningOperation(cts.Token));
              task.ContinueWith(t =&gt; Console.WriteLine("Operation cancelled"), TaskContinuationOptions.OnlyOnFaulted);
              task.Wait();
          }
          catch (AggregateException e)
          {
              //Handle
          }
      }
  
  
      void LongRunningOperation(CancellationToken token)
      {
          CancellationTokenRegistration registration = token.Register(
              () =&gt;
              {
                  throw new OperationCanceledException(token); 
              });
  
          using (registration)
          {
              // long running operation here
          }
      }
  </code></pre>