Best Practice LongRunning Task creation Best Practice LongRunning Task creation multithreading multithreading

Best Practice LongRunning Task creation


As you already mentioned, you can use the CancellationToken. Do it this way:

var cancellationTokenSource = new CancellationTokenSource();Task.Factory.StartNew(RemoveFromBlockingCollection                      , TaskCreationOptions.LongRunning                      , cancellationTokenSource.Token);  

And later in your code, you can cancel the task with:

cancellationTokenSource.Cancel();

In your long running task you can ask the token, if cancellation was requested:

if (cancellationTokenSource.Token.IsCancellationRequested)