1

With the following code, is there a better way to set up a UDP listen than a while(true) with Thread.Sleep(10)?

    public void Start()
    {
        socket.Bind(ip);
        while (true)
        {
            data = new byte[1024];
            receivedDataLength = socket.ReceiveFrom(data, ref Remote);
            raw = Encoding.ASCII.GetString(data, 0, receivedDataLength);
            row = new LogRow(raw);
            //Console.WriteLine(row.ClientIp);
            row_queue.Enqueue(row);
            Thread.Sleep(10);
        }
    }
Kyle Brandt
  • 26,938
  • 37
  • 124
  • 165

1 Answers1

3

ReceiveFrom is blocking. Thread will be suspended until data arrives. Unless Socket is in non-blocking mode.

Andrey
  • 59,039
  • 12
  • 119
  • 163
  • You should add that because `ReceiveFrom` is blocking, there's no need for the `Sleep`. – Jim Mischel Apr 06 '11 at 15:08
  • Ah okay, it must be my insert thread that is burning the CPU. Thanks I will drop the `sleep`. – Kyle Brandt Apr 06 '11 at 15:12
  • @Kyle Brandt♦ yes, `Spleep` is excessive. Run Application in debug and when burning starts pause debug and check each non-sleaping thread. – Andrey Apr 06 '11 at 15:34