Ricardo Peres
Ricardo Peres

Reputation: 14525

CancellationTokenSource or AutoResetEvent

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.

Upvotes: 3

Views: 3787

Answers (1)

Nitram
Nitram

Reputation: 6716

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.

Upvotes: 6

Related Questions