退出c#中的一个帖子(见详情) [英] Exit a thread in c# (see details)

查看:58
本文介绍了退出c#中的一个帖子(见详情)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如问题的标题所说,我想从启动它的同一个应用程序中杀死一个线程。



但是...线程是这样创建的方式:

new Thread => {...})。开始();

它工作正常,直到我关闭我的应用程序并且MyApplication.exe停止工作messageBox显示,因为该线程尚未杀了。



所以,我想问一下以这种方式关闭一个线程的正确方法是什么。

注意:我试过用currentThread.Abort();并且没有用。



代码示例(线程如何启动及其作用):

As the title of the question says, I want to kill a thread from the same application that started it.

But... the thread is created this way:
new Thread => {...}).Start();
It works good, until I close my application and a MyApplication.exe stopped working messageBox shows because the thread has not been killed.

So, I am asking what is the correct way to close a thread started in that way.
Note: I tried using the currentThread.Abort(); and did not work.

Code Sample(of how the thread is started and what it does):

private void btnListen_Click(object sender, EventArgs e)
       {
           server.Start(); // Starts Listening to Any IPAddress trying to connect to the program with port 1980
           MessageBox.Show("Waiting For Connection");
           new Thread(() => // Creates a New Thread (like a timer)
               {
                   client = server.AcceptTcpClient(); //Waits for the Client To Connect
                   MessageBox.Show("Connected To Client");
                   if (client.Connected) // If you are connected
                   {
                       ServerReceive(); //Start Receiving
                   }
               }).Start();
       }





提前致谢。 CCB



Thanks in advance. CCB

推荐答案

设置线程 IsBackground [ ^ ]属性在启动之前为true:当您的应用程序退出时,以这种方式标记的线程会被框架自动杀死。

如果不这样做,他们需要当应用程序的其余部分关闭时终止自己(这是为了让线程整齐地关闭一个优雅的方式)



哪里做我在我的代码中设置了那个bool?看到我的帖子没有被命名。



你在开玩笑吧? :笑:



Set the Thread IsBackground[^] property to true before you start it: threads marked in this way are automatically killed by the framework when your application exits.
If you don't, they need to terminate themselves when the rest of the app closes (this is to give a "graceful" way for the thread to shut down tidily)

"Where do I set that bool in my code? See that my thread has not been named."

You're kidding, right? :laugh:

Thread t = new Thread(() => // Creates a New Thread (like a timer)
    {
        client = server.AcceptTcpClient(); //Waits for the Client To Connect
        MessageBox.Show("Connected To Client");
        if (client.Connected) // If you are connected
        {
            ServerReceive(); //Start Receiving
        }
    });
t.IsBackground = true;
t.Start();


这篇关于退出c#中的一个帖子(见详情)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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