找到你要的答案

Q:Use case for foreground and background threads

Q:前台和后台线程的用例

In C# Threading, by default the new thread is a foreground thread.

But what is the use case of a background thread?

Also, on what does the main thread run -> on foreground or background thread?

C #线程,默认情况下,新的线程是前台线程。

但背景线程的使用情况是什么?

同时,对什么是主线程运行>;在前台或后台线程?

answer1: 回答1:

According to MSDN, the main difference between foreground and background threads is:

Background threads are identical to foreground threads with one exception: a background thread does not keep the managed execution environment running. Once all foreground threads have been stopped in a managed process (where the .exe file is a managed assembly), the system stops all background threads and shuts down.

So, the use case for background threads are, tasks that should not prevent your process from terminating.

If you use a thread to monitor an activity, such as a socket connection, set its IsBackground property to true so that the thread does not prevent your process from terminating.

Considering the difference, UI thread should be foreground so that it keeps the process running until UI shuts down. If it was a background thread, the process stopped running as soon as no other foreground thread was running.

Edit:

Since you can signal the foreground threads when process is supposed to terminate, I don't see any special use case that cannot be implemented using foreground threads only. Since those thread may need to be informed about termination to free resources or perform an action, manually signaling them (rather than relying on the fact that they will be terminated because there are background) could be a better choice. But making them background would be a "Just in case" thing, that if for some reason they doesn't get signaled, they do not prevent process from terminating.

根据MSDN,前台和后台线程之间的主要区别是:

Background threads are identical to foreground threads with one exception: a background thread does not keep the managed execution environment running. Once all foreground threads have been stopped in a managed process (where the .exe file is a managed assembly), the system stops all background threads and shuts down.

因此,后台线程的用例是不应该阻止进程终止的任务。

If you use a thread to monitor an activity, such as a socket connection, set its IsBackground property to true so that the thread does not prevent your process from terminating.

考虑到差异,UI线程应该是前台,以便它保持进程运行,直到UI关闭。如果它是后台线程,则进程在没有其他前台线程运行时停止运行。

编辑:

由于进程可以终止时,您可以指示前台线程,我没有看到任何特殊的用例,不能使用前台线程来实现。由于这些线程可能需要通知终止的自由资源或执行一个动作,手动通知他们(而不是依赖的事实,他们将被终止,因为有背景)可能是一个更好的选择。但是,使他们的背景将是一个“以防万一”的事情,如果因为某些原因,他们没有得到信号,他们不阻止进程终止。

c#  multithreading