C# 线程在另一个类中启动

本文关键字:启动 另一个 线程 | 更新日期: 2023-09-27 18:32:21

我有一个主窗体类和另一个类。在第二类中,我有一个线程循环:

    public void StartListening()
    {
        listening = true;
        listener = new Thread(new ThreadStart(DoListening));
        listener.Start();
    }

    // Listening for udp datagrams thread loop
    /*=====================================================*/
    private void DoListening()
    {
        while (listening)
        {
            IPEndPoint remoteIPEndPoint = new IPEndPoint(IPAddress.Any, port);
            byte[] content = udpClient.Receive(ref remoteIPEndPoint);
            if (content.Length > 0)
            {
                string message = Encoding.ASCII.GetString(content);
                delegMessage(message);
            }
        }
    }
    // Stop listening for udp datagrams
    /*=====================================================*/
    public void StopListening()
    {
        lock (locker)
        {
            listening = false;
        }
    }

在主窗体类中,我在类构造函数中开始侦听

       udp.StartListening();

而且,在这个主窗体类中,我也有键钩事件。在这种情况下,我想停止线程在第二个类中运行。

    private void hook_KeyPressed(int key)
    {
        if (key == (int)Keys.LMenu)
            altPressed = true;
        if (key == (int)Keys.F4 && altPressed == true)
        udp.StopListening();
    } 

不幸的是,线程仍在运行。你对此有一些想法吗?

谢谢。

C# 线程在另一个类中启动

您的线程在byte[] content = udpClient.Receive(ref remoteIPEndPoint);行处阻塞。 接收方法会阻止,直到收到某些内容。

您应该改用异步版本 (BeginReceive)。

此外,代码中的另一个缺陷 - 您在没有任何同步的情况下检查停止条件。这里:

   private void DoListening()
   {
    while (listening){ //this condition could stuck forever in 'false'
   }

实际上,如果没有内存屏障,就无法保证正在运行DoListening线程会看到来自其他线程的 var listening更改。您至少应该在此处使用锁定(这提供了内存屏障)

正如@igelineau指出的那样 - 您的代码在接收调用时被阻止。 如果您不想沿着异步路由(我建议)走下去,只需在停止侦听方法中向udp端口发送一些内容即可。