C# 后台线程未按其任何定义中所述工作
定义:当主线程离开执行时,后台线程停止执行 当我尝试时,即使主线程完成了执行,后台线程也没有停止执行。请检查上述链接中为后台线程提供的示例 使用制度; 使用系统线程 类GFG{C# 后台线程未按其任何定义中所述工作,c#,multithreading,background-thread,C#,Multithreading,Background Thread,定义:当主线程离开执行时,后台线程停止执行 当我尝试时,即使主线程完成了执行,后台线程也没有停止执行。请检查上述链接中为后台线程提供的示例 使用制度; 使用系统线程 类GFG{ // Main method static void Main(string[] args) { // Creating and initializing thread Thread thr = new Thread(mythread); // Name of the thread
// 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!!");
}
线程作为“主”执行上下文的一部分启动。因此,退出“主程序”后,“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
}
如果希望代码在主代码退出初始代码后保持加载和运行,则需要使用不同的策略。您需要以“进程”的形式启动代码
由于问题不清楚,我无法给出完整的答案
您的程序正在做它需要做的事情。
已附加快照。结果如文件所示。
我使用的是VS 2019、.Net 3.5请将您的代码发布到问题中,而不仅仅是示例。您是否可以检查在
Start()
之前设置IsBackground
属性?在屏幕截图中,我可以看到代码示例中不存在的行Console.ReadLine()
。这一行完全不同。@TheodorZoulias控制台窗口在完成执行后立即消失。我们无法看到输出结果。我添加了Readline,因此它将等待一些用户输入。因此,我们可以检查输出。是的,你可能是对的。当我们正在等待读取某些内容时,主线程仍然处于活动状态。当主线程处于活动状态时,后台线程也会完全执行。感谢在Visual Studio内部运行控制台应用程序时,您可以通过在不进行调试的情况下启动它们(使用Ctrl+F5)来防止它们关闭。信息按任意键继续代码>将在应用程序完成后出现在控制台中。请尝试。还是一样,我刚测试过。该属性可以在线程生命周期之前或期间的任何时候设置,并具有预期的效果。但他显然希望他的线程每次都是背景线程,而不仅仅是一部分。首先,我的目的是了解背景线程和前景线程之间的区别。正如我的问题所说,后台线程没有按照其定义工作。我给你的代码取自著名的极客博客。它没有像前面提到的那样起作用。它并没有完全按照我说的去做。请检查我提到的预期输出。然后,你说“线程作为主线程的一部分启动”,如果我没有错的话,所有线程都必须使用主线程创建。那么我们如何创建新的线程呢?附上我得到的答案截图。请检查..Net 3.5?那是旧版本!我想我犯了个错误。控制台窗口在完成执行后立即消失。我添加了Readline,因此它将等待一些用户输入。因此,我们可以检查输出。当我们正在等待读取某些内容时,主线程仍然处于活动状态。当主线程处于活动状态时,后台线程也会完全执行。谢谢谢谢你的帮助,伙计