主线程完成后子线程不工作

Child Thread not working after main thread finishes

我正在开发一个应用程序,用于侦听来自不同线程的队列,但我遇到了线程管理方面的问题。我从我的主应用程序启动了一个后台线程。它工作正常,但在主应用程序完成后,子线程就会终止。主应用程序完成后是否有继续子线程的方法。

我像下面这样开始线程。

Thread myNewThread = new Thread(() => Executer.ProcessQueueMessages());
myNewThread.IsBackground = true;
myNewThread.Start();

正如其他人在评论中所说,但决定不提供完整答案,后台线程在父线程终止后不会继续 运行。

如果你想让这个线程保持运行ning那么你需要将它设置为前台线程。

此来源:http://www.c-sharpcorner.com/UploadFile/ff0d0f/working-of-thread-and-foreground-background-thread-in-C-Sharp730/

很好地解释了差异并给出了示例。摘自该州;

In C# there're the following 2 kinds of threads.

  1. Foreground Thread
  2. Background Thread

Foreground Thread

Foreground threads are those threads that keep running even after the application exits or quits. It has the ability to prevent the current application from terminating. The CLR will not shut down the application until all Foreground Threads have stopped.

Background Thread

Background Threads are those threads that will quit if our main application quits. In short, if our main application quits, the background thread will also quit. Background threads are views by the CLR and if all foreground threads have terminated, any and all background threads are automatically stopped when the application quits. By default every thread we create is a Foreground Thread.

当进程退出时,O/S 清除所有打开的句柄、运行 线程和任何其他锁定的资源。如果它不这样做,那么当一个进程行为不当时,将很难纠正系统。所以你问的是不可能的。

如果您有一个很长的 运行 作业要执行并且您想确保它在退出程序之前完成,最常见的方法是 return 一个任务并在退出之前等待它,例如要开始任务,请执行以下操作:

var task = Task.Run( () => DoSomethingThatTakesALongTime() );

为确保完成,请执行以下操作:

await task;

或者这样:

task.GetAwaiter().GetResult();

您可以使用 Join() 让当前线程等待子线程 (myNewThread) 完成。

Thread myNewThread = new Thread(() => Executer.ProcessQueueMessages());
myNewThread.IsBackground = true;
myNewThread.Start();
myNewThread.join()