Best Practice LongRunning Task creation

.net, .net-4.0, c#, multithreading, task-parallel-library

Solution

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)

Problem

Is this a good design for a background thread that needs to be run using the Task API in .Net 4? My only concern is if we want to cancel that task how I would do it? I know I can just set `ProgramEnding` to `true` but I know there is a `CancellationToken` in the Task API. This is just an example sample of code so that one thread will be adding to a collection and another thread will be removing from it. The Task is setup as LongRunning as this needs to be running continuously whilst the program is running ``` private void RemoveFromBlockingCollection() { while (!ProgramEnding) { foreach (var x in DataInQueue.GetConsumingEnumerable()) { Console.WriteLine("Task={0}, obj={1}, Thread={2}" , Task.CurrentId, x + " Removed" , Thread.CurrentThread.ManagedThreadId); } } } private void button1_Click(object sender, EventArgs e) { DataInQueue = new BlockingCollection<string>(); var t9 = Task.Factory.StartNew(RemoveFromBlockingCollection , TaskCreationOptions.LongRunning); for (int i = 0; i < 100; i++) { DataInQueue.Add(i.ToString()); Console.WriteLine("Task={0}, obj={1}, Thread={2}", Task.CurrentId, i + " Added", Thread.CurrentThread.ManagedThreadId); Thread.Sleep(100); } ProgramEnding = true; } ``` UPDATE: I have found that I can remove the ProgramEnding boolean and use DataInQueue.CompleteAdding which which bring the thread to an end.

Original source

Related problems