制作线程前景VS Thread.Join() [英] Making a thread Foreground VS Thread.Join()

查看:74
本文介绍了制作线程前景VS Thread.Join()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果foreground thread是防止进程终止直到属于该进程的所有前台线程都终止的线程,并且Join方法阻塞了调用线程直到线程终止,那么之间的真正区别是什么两种技术?

If a foreground thread is a thread that prevents a process from terminating until all foreground threads belonging to the process have finished, and if the Join method Blocks the calling thread until a thread terminates, then what's really the difference between the two techniques ?

前台线程:

static void Main()
    {
        Thread foregroundThread = 
            new Thread(new ThreadStart(SomeMethod));
        foregroundThread.Name = "ForegroundThread";

        foregroundThread.IsBackground = false;

        foregroundThread.Start();
    } 

Join()方法:

static void Main() 
    {
        Thread thread = 
                new Thread(new ThreadStart(SomeMethod));

        thread.Name = "Thread";
        thread.Start();
        thread.Join();
    }

两种方法之间有区别吗?

Is there a difference between the two approaches ?

推荐答案

区别在于,当一个进程关闭/退出/停止时,它需要其所有前台线程都停止才能安全终止.您的第二个代码虽然给出的结果与第一个代码相同,但是在行为方式上有所不同. Join阻止执行您的主线程(该进程的前台线程),除非您的后台线程完成执行,否则无法安全地终止该进程.

The difference is that when a process shuts down/exits/stops it needs all its foreground threads to stop before it can safely terminate. Your second code although it gives the same result as the first one, it differs in the way it behaves. Join blocks the execution of the your main thread which is a foreground thread of that process making it impossible to safely terminate the process unless your background thread finishes execution.

当您尝试从另一个后台线程启动线程时,前台线程的主要好处是.

The main benefit of foreground threads comes when you try starting threads from another background thread.

假设您正在尝试编写一个将重要数据写入磁盘的线程,并且该线程是从后台线程启动的.现在,您需要确保如果用户决定关闭您的进程,则在完成其指定任务之前,写入数据的线程不会在中途异常终止.

Say you are trying to write a thread that writes vital data to disk and that thread gets started from a background thread. Now you need to make sure that if the user decides to close your process, that the thread writing the data will not abnormally terminate mid way before completing its designated task.

想象一下您有这样一种情况:

Imagine you have such a scenario:

static void Main()
{
   Thread backgroundThread = new Thread(new ThreadStart(SomeMethod));
   thread.IsBackground = true;
   backgroundThread.Start();
} 


static void SomeMethod() 
{
   Thread thread = new Thread(new ThreadStart(SomeOtherMethod));
   thread.Name = "ForegroundThread";
   thread.IsBackground = false;
   thread.Start();
}

尽管您的主线程在没有等待或联接的情况下创建了后台线程,但是您的进程将永远不会退出,直到由后台线程创建的前台线程退出为止.

Here although your main thread creates a background thread without a wait or join, your process will never exit until the foreground thread created by the background thread exits.

这篇关于制作线程前景VS Thread.Join()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆