后台线程未按其任何定义中所述工作

Background Thread is not working as mentioned in any of its definitions

定义:当主线程退出执行时,后台线程停止执行。

Source

我试了一下,主线程执行完了,后台线程也没有停止执行。请检查上面 link 中为后台线程提供的示例。

使用系统; 使用 System.Threading;

class GFG {

// Main method 
static void Main(string[] args) 
{ 
    // Creating and initializing thread 
    Thread thr = new Thread(mythread); 

    // Name of the thread is Mythread 
    thr.Name = "Mythread"; 
    thr.Start(); 

    // IsBackground is the property of Thread 
    // which allows thread to run in the background 
    thr.IsBackground = true; 

    Console.WriteLine("Main Thread Ends!!"); 
} 

// Static method 
static void mythread() 
{ 

    // Display the name of the  
    // current working thread 
    Console.WriteLine("In progress thread is: {0}", 
                        Thread.CurrentThread.Name); 

    Thread.Sleep(2000); 

    Console.WriteLine("Completed thread is: {0}", 
                      Thread.CurrentThread.Name); 
} 

}

预期输出: 正在进行的线程是:Mythread 主线程结束!!

我没有得到他们在那里提到的输出。我得到了所有三个控制台输出,如

正在进行的线程是:Mythread 主线程结束。 完成的线程是:Mythread

编辑:有人说无法重现问题。只有我遇到这个问题吗?

IsBackground属性放在线程开始之前,像这样:

// Main method 
static void Main(string[] args) 
{ 
    // Creating and initializing thread 
    Thread thr = new Thread(mythread); 

    // Name of the thread is Mythread 
    thr.Name = "Mythread"; 

    // IsBackground is the property of Thread 
    // which allows thread to run in the background 
    thr.IsBackground = true; 
    thr.Start();

    Console.WriteLine("Main Thread Ends!!"); 
}

线程作为 "main" 执行上下文的一部分启动。所以在退出时 "main" "thr" 将被收集并终止,因为它是主程序的即时部分。其次 "thr" 启动,休眠 2 秒,然后退出,完全按照您的指示执行。如果 "thr" 打算保留 运行 那么它需要包含某种循环和信号实现以告诉它不再需要时退出。

我还没有尝试过这个,但添加以下内容进行实验。它可能更接近您尝试做的事情,但这不是一个好的方法。

static void mythread() 
{ 

  Do{
// Display the name of the  
// current working thread 
Console.WriteLine("In progress thread is: {0}", 
                    Thread.CurrentThread.Name); 

Thread.Sleep(2000); 

Console.WriteLine("Completed thread is: {0}", 
                  Thread.CurrentThread.Name); 
 }
While(sinalvariable) // signal variable changed by some other code 
                      //To tell thread  to exit the whileloop

} 

如果您希望代码保持加载状态并且 运行 在主程序退出初始代码后,您需要使用不同的策略。您需要将代码作为 "Process" 启动。

由于问题不明确,我无法给出完整的答案。

您的程序正在做它需要做的事情。

附上快照。结果与文档中预期的一样。 我正在使用 VS 2019、.Net 3.5