C# 多线程概念:“threading”会在所有子线程完成执行之前执行return语句吗?

C# 多线程概念:“threading”会在所有子线程完成执行之前执行return语句吗?,c#,multithreading,C#,Multithreading,我有一个最近困扰我的线程问题。看看下面的C代码示例 public void threading() { for(int count =0; count< 4; count++) { Thread childThread = new Thread(childThread); childThread.start() } return; } public void childThread() { // Do al

我有一个最近困扰我的线程问题。看看下面的C代码示例

 public void threading()
 {
     for(int count =0; count< 4; count++)
     {
        Thread childThread = new Thread(childThread);
        childThread.start()
     }

     return;
 }

public void childThread()
{
 // Do alot of work 
}
public void threading()
{
对于(int count=0;count<4;count++)
{
线程childThread=新线程(childThread);
childThread.start()
}
返回;
}
公共无效子线程()
{
//做很多工作
}

由于
threading
方法中的循环后面有一个return语句,因此
threading
会在所有子线程完成执行之前执行return语句吗?我在某个地方读到,线程与fork不同,因为它们不创建单独的内存区域,所以死线程会在哪里结束

线程会在所有子线程之前执行return语句吗 线程是否完成执行

也许是的。可能不会。这完全取决于
childThread
方法执行所需的时间。若您的
childThread
方法花费的时间确实较少,那个么在
threading
方法中执行return语句之前,所有四个线程都会完成

另一方面,如果需要很长时间,那么即使
threading
方法完成执行或返回到
Main
之后,线程也可以继续异步执行

您还需要知道一件事:

默认情况下,他们创建的所有线程都是后台线程。因此,只要您的流程还活着,它们就会存在。如果您的主GUI线程即将结束,那么这四个线程也将被抛出并中止。因此,至少一个前台线程必须处于活动状态,您的四个线程才能继续执行
childThread
方法以运行到完成


就内存而言,创建的每个线程都有自己的堆栈内存区域,但它们共享公共堆内存。此外,无论是线程的堆栈内存还是堆内存,它都肯定位于进程自己的地址空间的外围。

如果要强制所有子线程在
线程
方法返回之前终止,可以在线程上使用
Join
方法,例如

public void Threading()
{
    List<Thread> threads = new List<Thread>();

    // start all threads
    for(int count =0; count< 4; count++)
    {
        Thread childThread = new Thread(ChildThread);
        childThread.start();
        threads.Add(thread);
    }

    // block until all threads have terminated
    for(int count =0; count< 4; count++)
    {
        threads[count].Join();
    }

    // won't return until all threads have terminated
    return;
}

public void ChildThread()
{
    // Do alot of work 
}
public void Threading()
{
列表线程=新列表();
//启动所有线程
对于(int count=0;count<4;count++)
{
线程childThread=新线程(childThread);
childThread.start();
线程。添加(线程);
}
//阻塞,直到所有线程终止
对于(int count=0;count<4;count++)
{
线程数[count]。连接();
}
//在所有线程终止之前不会返回
返回;
}
公共无效子线程()
{
//做很多工作
}

在所有子线程完成执行之前执行return语句是否可能与“will
threading
重复?”-是的,因为它在一个单独的线程中运行。你说的“dead thread”是什么意思?它是fire and forget代码。很少是正确的,您不知道线程何时完成,并且很少有希望正确处理错误。这让你问了这个问题。请考虑任务类。很棒。它如何处理“在所有子线程完成执行之前,线程是否会执行return语句?”我很感激这并没有回答字面上的问题。对“will X do Y?”问题的另一种解释是“我如何才能使X do Y?”,这就是问题的答案(“我如何才能使其使方法仅在所有子线程完成执行后返回?”)。