Zerowalker
Zerowalker

Reputation: 767

Thread loop, closing it in an Optimal way

Okay well, here is the code:

    private void Receivev2()
    { 
        try
        {
            using (UdpClient udpclient = new UdpClient(1500))
            {
                while (connect == true)
                {

                    byte[] byteData = udpclient.Receive(ref remoteEP);
                    waveProvider.AddSamples(byteData, 0, byteData.Length);
                    if (Record == true)
                    {
                        waveWriter.Write(byteData, 0, byteData.Length);
                    }

                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "VoiceChat-Receive ()", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

It´s on a Thread, and well, it receives data from udp and plays it, nothing weird.

My problem however, is to make it stop normally, or well, don´t know how to put it.

But let´s say, i start the thread and it loops. Then if i close my application, the application won´t "close", as the thread isn´t closing.

Now to solve that, i use IsBackground = true.

But i am not sure if that is an optimal way to do it, it feels like it will just force it to shut down, like ProcessKill or something.

Maybe it is the correct way, i don´t know.

Please give me advice on this.

Upvotes: 2

Views: 158

Answers (2)

Brian Gideon
Brian Gideon

Reputation: 48949

The trick is call UdpClient.Close. This will cancel any pending operations and "poke" the Receive method into throwing a SocketException if it is blocking. Obviously, you will have to call Close from another thread which means you will need to refactor your code a bit so that udpclient is no longer a local variable. You will also need to set connect to false so that the loop ends.

So to summarize the steps are as follows.

  • Call Close to prevent Receive from blocking.
  • Set connect to false.
  • Refactor your code to make the above possible.

Upvotes: 2

tiger
tiger

Reputation: 1

If it's a import thread, you'd better not set IsBackground , because the main thread stop,It will be forced stop

stop thread step:

1 set connect=false ,than main thread sleep a while untill it stop 2 if the thread still alive, you can abort it ,this step is not necessary 3 than join the back thread to main thread

just like this:

        connect= false;

        Thread.Sleep(200);
        if (thread1 != null)
        {
            if (thread1 .IsAlive)
            {
                thread1 .Abort();
                thread1 .Join();
            }
        }

Upvotes: 0

Related Questions