如果线程对象在线程例程完成之前消失,将会发生什么?

时间:2018-07-11 10:52:39

标签: c# .net multithreading

我对线程对象有疑问。 假设我在“ pendingThread”上执行“ NewThread()”方法创建了一个新的Thread对象并启动了该对象。 NewThread()方法需要花费大量时间才能返回。如果在先前启动的线程返回之前重新初始化了“ pendingThread”会怎样? 它会中止还是中止?

很高兴看到您的答案

    public void Threaded_accept()//this function accepts client. It's executed on the new thread
    {
        bool pending = this.listen_socket.AcceptAsync(this.accept_args);// If completed Asynchronously
        //On_Accept_Completed is called Automatically

        if (pending == false)// If AcceptAsync was completed synchronously
        {

            this.pendingThread = new Thread(StartNewThread);
            pendingThread.Start();//This is for keep receiving requests while Thread is working
            //TODO What happens when pendingThread is reinitialized while pending Thread was running?
        }

        flow_control_event.WaitOne();//wait until scoket is accepted

    }

1 个答案:

答案 0 :(得分:2)

前景线程一直运行,直到它们正常退出(通过从作为线程启动函数给出的函数返回)或异常退出(由于异常,包括通过Thread.Abort从其他地方注入异常)整个过程被拆除。 1

您无需保留对特定Thread对象的引用就可以实现此目的。


1 背景线程实际上是相同的,只需要记住,当所有的前台线程都退出时,这可能是整个过程被拆除的原因之一。 / p>