【问题标题】:Kill multi threading Server's thread c#杀死多线程服务器的线程c#
【发布时间】:2017-01-22 12:07:22
【问题描述】:

我有一个启动服务器线程的程序,在该线程中我等待用户连接,但有时(如果用户按“E”)我想关闭该服务器线程但它不工作。我试过了

'thread'.abort() - but it's freezing and not stopping the thread 

这里是服务器代码:

 private void start()
    {
        try
        {
            this.serverSocket = new TcpListener(8888);                      // creating the Server TCP socket 
            this.clientSocket = default(TcpClient);                         // creating the User socket variable  

            // starting the server
            this.serverSocket.Start();

            Console.WriteLine("->> server started");                        // printing to log 

            // for always 
            while (true)
            {
                counter += 1;                                               // new user 
                this.clientSocket = this.serverSocket.AcceptTcpClient();    // accepting user 
                Console.WriteLine(" ->> User connected");                   // printing to log 
                // User creatinon
                ConnectedUser user = new ConnectedUser(this.clientSocket);
                user.startListerner();
            }

            this.clientSocket.Close();
            this.serverSocket.Stop();
            Console.WriteLine(" >> " + "exit");
            Console.ReadLine();
        }
        catch
        {
            Console.WriteLine("Error launching the Server");
        }

    }

我是这样运行的:

this.server = new Thread(start);
server.Start();

我想终止它,我该怎么做?

【问题讨论】:

标签: c# multithreading function server


【解决方案1】:

您必须使用CancellationTokenSource 来指示您的线程自行终止。不推荐使用Thread.Abort,因为它会终止线程而没有先让其正确清理。

要使用取消令牌,您需要创建一个CancellationTokenSource 的实例,然后将令牌传递给您的线程函数(或封装新线程状态的对象。然后您可以在线程函数内部检查IsCancellationRequested定期查看令牌的属性以查看线程是否应该关闭。您可以将相同的取消令牌传递给 I/O 函数,以便它们尝试取消阻塞操作。

阅读this question/ answers 了解更多关于Thread.Abort 可能导致的问题的详细信息。特别阅读 Eric Lippert 对这个问题的回答,他提到永远不要启动一个你不能礼貌地停止的线程。

【讨论】:

    猜你喜欢
    • 2021-03-12
    • 1970-01-01
    • 2019-10-12
    • 1970-01-01
    • 2023-04-06
    • 2020-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多