简体   繁体   中英

C# thread started in another class

I have one main form class and another class. In the second class, I have a thread loop:

    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;
        }
    }

In main form class, I start this listening in class constructor

       udp.StartListening();

And than, in this main form class, I have key hook event, too. In this event, I wan to stop thread running in the second class.

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

Unfortunetely, the thread is still running. Do you have some ideas about this??

Thank you very much.

Your thread is blocking at the byte[] content = udpClient.Receive(ref remoteIPEndPoint); line. The Receive method blocks until something is received.

You should use the asynchronous version ( BeginReceive ) instead.

Also, another flaw in your code - you check for the stopping condition without any synchronization. Here:

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

Actually, without a memory barrier, there is no guarantee, that a thread, that is running DoListening will ever see the change to listening var from other thread. You should at least use locking here (which provides memory barrier)

As @igelineau pointed out - your code is blocking on the receive call. If you don;t want to go down the async route (which I'd recommend) just send something to the udp port in your stop listening method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM