EDIT: Updated for .NET 4.5 and later, more at the bottom of the post.
CancellationToken the thing you want to use. Checking IsCancellationRequested may look like a pain, but it provides a clean way to handle cancellation, as opposed to creating a thread and then aborting it and the need to handle the thread interruption exception in all code that runs in parallel.
var cts = new CancellationTokenSource(); var token = cts.Token; var task = Task.Run(() => {
This may add some confusion to the delegate, but the revocation itself is so simple that I never needed to use anything coarser than the cancellation token source. You did not say why you would like to avoid this, so if you do not have a hard limit, I would stick to the cancellation markers.
As with @ipavlu's comment, for a simple use case, it is much better to use Task.Run instead of the original Task.Factory.StartNew to disable asynchronous operation. They provide the same basic functionality, but Task.Run has safer defaults and better support for new async functions, and Task.Factory.StartNew can be used to indicate advanced behavior. More information here: https://blogs.msdn.microsoft.com/pfxteam/2011/10/24/task-run-vs-task-factory-startnew/
source share