Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to guarantee a new thread is created when using the Task.StartNew method

From what I can tell I have misleading bits of information. I need to have a separate thread running in the background.

At the moment I do it like this:

var task = Task.Factory.StartNew
         (CheckFiles
          , cancelCheckFile.Token
          , TaskCreationOptions.LongRunning
          , TaskScheduler.Default);//Check for files on another thread

 private void CheckFiles()
 {
    while (!cancelCheckFile.Token.IsCancellationRequested)
    {
        //do stuff
    }
 }

This always creates a new thread for me. However after several discussions even if it is marked as LongRunning doesn't guarantee that a new thread will be created.

In the past I have done something like this:

thQueueChecker = new Thread(new ThreadStart(CheckQueue));
thQueueChecker.IsBackground = true;
thQueueChecker.Name = "CheckQueues" + DateTime.Now.Ticks.ToString();
thQueueChecker.Start();


private void CheckQueue()
{
   while (!ProgramEnding)
   {
            //do stuff
   }
}

Would you recommend that I go back to this approach to guarantee a new thread is used?

like image 724
Jon Avatar asked Nov 07 '11 17:11

Jon


People also ask

Does task WhenAll create new thread?

WhenAll does not create a new thread. A "task" does not necessarily imply a thread; there are two types of tasks: "event" tasks (e.g., TaskCompletionSource ) and "code" tasks (e.g., Task. Run ). WhenAll is an event-style task, so it does not represent code.

What is the difference between Task run() and Taskfactory StartNew() methods?

Run(action) internally uses the default TaskScheduler , which means it always offloads a task to the thread pool. StartNew(action) , on the other hand, uses the scheduler of the current thread which may not use thread pool at all!

Does async create a new thread?

The async and await keywords don't cause additional threads to be created. Async methods don't require multithreading because an async method doesn't run on its own thread. The method runs on the current synchronization context and uses time on the thread only when the method is active.

What does Task factory StartNew do?

StartNew(Action<Object>, Object, CancellationToken, TaskCreationOptions, TaskScheduler) Creates and starts a task for the specified action delegate, state, cancellation token, creation options and task scheduler.


1 Answers

The default task scheduler ThreadPoolTaskScheduler does indeed always create a new thread for long running task. It does not use the thread pool as you can see. It is no different as the manual approach to create the thread by yourself. In theory it could happen that the thread scheduler of .NET 4.5 does something different but in practice it is unlikely to change.

protected internal override void QueueTask(Task task)
{     
  if ((task.Options & TaskCreationOptions.LongRunning) != TaskCreationOptions.None)
  {
    new Thread(s_longRunningThreadWork) { IsBackground = true }.Start(task);
  }
  else
  {
    bool forceGlobal = 
        (task.Options & TaskCreationOptions.PreferFairness) != TaskCreationOptions.None;
     ThreadPool.UnsafeQueueCustomWorkItem(task, forceGlobal);
  }
}
like image 54
Alois Kraus Avatar answered Oct 20 '22 14:10

Alois Kraus