使用Task.StartNew方法时,如何保证一个新的线程创建线程、方法、Task、StartNew

2023-09-08 09:03:58 作者:所遇皆良人

从我可以告诉我的信息误导位。我需要有在后台运行一个单独的线程。

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
    }
 }

这始终是我创建了一个新的线程。后即使它被标记为LongRunning并不保证一个新的线程将创建多次讨论然而

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?

推荐答案

LongRunning仅仅是一个暗示,调度程序 - 如果你绝对必须有一个新的线程,你必须创建一个

LongRunning is just a hint to the scheduler - if you absolutely must always have a new Thread, you will have to create one.