首页 > 解决方案 > 如果 Thread 对象在线程例程完成之前消失会发生什么?

问题描述

我有一个关于线程对象的问题。假设我在 'pendingThread' 上创建了一个新的 Thread 对象,执行 'NewThread()' 方法并启动它。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

    }

标签: c#.netmultithreading

解决方案


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

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


1后台线程其实是一样的,只是需要记住,当所有的前台线程都退出时,这可能是整个进程被拆除的原因之一。


推荐阅读