0

I am trying to make Udp socket that sends to specific IP and Port without using Thread.

When i start Debug, UI Freeze. Start Button doesn't change to stop.

Is there any solution?

private void start_button_click(object sender, RoutedEventArgs e)
{
    if (string.IsNullOrEmpty(ip_textbox.Text) || string.IsNullOrEmpty(port_textbox.Text)) ; 
    // if textbox empty it doesn't work anything
    else
    {
        if ((string)start_button.Content == "Stop") 
        // if Start button content is stop, it should stop.
        {
            start_button.Content = "Start";
        }
        else
        //if Start button Content is Start, it should begin
        {
            start_button.Content = "Stop";
            Data_Sender(ip_textbox.Text, Convert.ToInt32(port_textbox.Text));
        }
    }
}
private void Data_Sender(string ip, int port)
{
    int data_sequence = 1; 
    // data sequence

    byte[] data = new byte[64]; 
    // 64byte data 
    byte[] byte_data_seq = new byte[4]; 
    // int sequence to byte
    byte[] datagram = new byte[1024]; 
    // data + byte_data_seq
    List<byte> datagram_list = new List<byte>();

    IPEndPoint ep = new IPEndPoint(IPAddress.Parse(ip), port);
    Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

    while (true)
    {
        random.NextBytes(data);

        byte_data_seq = BitConverter.GetBytes(data_sequence);
        datagram_list.AddRange(byte_data_seq);
        datagram_list.AddRange(compressed_data);

        datagram = datagram_list.ToArray();
        datagram_list.Clear();

        client.SendTo(datagram, ep);

        Thread.Sleep(cycle);
    }
}
KooEunBam
  • 17
  • 1
  • 8
  • 2
    Try it again with using a thread? You put it explicitly in the heading so you obviously have already a feeling that this is the problem. And you are correct. You might look up at least at async/await. But i doubt Socket has a Task aware surface. So a more classic approach with threads (or asynchrounous code) might be needed. – Ralf May 16 '22 at 10:49
  • 2
    An endless loop with Thread.Sleep will block the UI thread. Use a timer or a loop with `await Task.Delay(cycle)`. – Clemens May 16 '22 at 11:06

0 Answers0