3

Modern .NET APIs use CancellationTokenSource and CancellationToken for cancelling jobs across threads. Is there any reason to use these instead of the "old" AutoResetEvent and ManualResetEvent? I imagine that CancellationToken encapsulates something similar, as exposed by its WaitHandle property.

Ricardo Peres
  • 13,724
  • 5
  • 57
  • 74
  • possible duplicate of [this](http://stackoverflow.com/questions/13476528/stopping-a-thread-manualresetevent-volatile-boolean-or-cancellationtoken) – ntohl Aug 27 '15 at 11:27

1 Answers1

6

Well yes. The CancellationTokenSource uses a ManualResetEvent internally to handle the reporting of the cancellation event.

Still you should prefer to use the CancellationTokenSource for cancelling stuff for a couple of reasons:

  1. It is right in the name. It cancels stuff. This makes for a easier read since it is clear right from the start what a instance of this class is used for.
  2. Many of the classes that are part of the .NET framework and that can be cancelled use the CancellationTokenSource. Especially many things in System.Threading (and sub-packages)
  3. While using a ManualResetEvent the CancellationTokenSource does a couple of things to optimize things internally. Lazy initialization and such things. I hope that makes it just a little faster and run with less overhead under some conditions.
Nitram
  • 6,486
  • 2
  • 21
  • 32