Click here to Skip to main content
15,890,506 members
Please Sign up or sign in to vote.
4.50/5 (2 votes)
See more:
I am reading data in bytes on one UDP client port which is broadcast by other server.
I have created a single thread with sleep time it works when data incoming is slow but when data incoming incresaes then its memory use go high and terminate with unknown error.

I want help on this like thread should manage in such a manner after completion of one job come to next job not only depend on sleep time, so my threading could run smoothly.

Thanks.

 public partial class FormUDP : Form
    {
        UdpClient listener = new UdpClient(9871);
        IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, 0);

        bool ProcessStatus; //process
        Thread _UDPthread; //Thread

     private void btn_rcve_Click(object sender, EventArgs e)
       {
           ThreadStart _process = new ThreadStart(receivemessages);
           _UDPthread = new Thread(_process);
           ProcessStatus = true;
           _UDPthread.Start();

       }


private void receivemessages()
       {
           MessageBox.Show("start");
           while (ProcessStatus)
           {
               try
               {
                   if (listener.Available > 0)
                   {
                       byte[] buffer = listener.Receive(ref groupEP);
                       ///**Start convert **//
                       TBCastMessageHeader bcastHeader = new TBCastMessageHeader();
                       IntPtr bcastHeaderPtr;
                       bcastHeaderPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(TBCastMessageHeader)));
                       Marshal.Copy(buffer, 0, bcastHeaderPtr, buffer.Length);
                       bcastHeader = (TBCastMessageHeader)(Marshal.PtrToStructure(bcastHeaderPtr, typeof(TBCastMessageHeader)));  


                  try
                      {
                          switch (bcastHeader.MessageCode)
                          {
                           case 10:
                                     // convert byte to structure and insert into sql database
                                   break;
                          }
                        }
                      catch (Exception ex)
                        { }
                        finally { Marshal.FreeHGlobal(bcastHeaderPtr); C.Collect();}
               if (ProcessStatus)
                {
                    Thread.Sleep(new TimeSpan(0, 0, 0, 0, 5)); // 5 miliseconds
                }
 
        }

// Structure defined
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 0x1)]
    public struct TBCastMessageHeader
    {
        public ushort MessageCode;
        public uint TimeStamp;
        public ushort MessageLength;
        public sbyte NumberOfDecimals;
        public ushort Reserved;
    }


 }
Posted
Updated 18-Mar-11 12:20pm
v4
Comments
Dalek Dave 18-Mar-11 18:21pm    
Edited for Grammar and Readability.

1 solution

Using sleep time is pointless. In your case, you should create a thread from the very beginning (not by click) and keep it sleeping (actually, in wait state not using any CPU time until awaken) using thread synchronization primitives, like System.Threading.EventWaitHandle. More advanced use would be using a generic blocking queue with elements each representing a "task" for a thread, see my Tips/Trick article: Simple Blocking Queue for Thread Communication and Inter-thread Invocation[^].
Best way to create a thread is using wrapper, here is how: How to pass ref parameter to the thread[^].

For a general design schema, see my Answers to similar Questions:

Control.Invoke() vs. Control.BeginInvoke()[^]
Problem with Treeview Scanner And MD5[^]
Multple clients from same port Number[^] (this one is for TCP, but many recommendations are still valid for your case)
How to get a keydown event to operate on a different thread in vb.net[^]

—SA
 
Share this answer
 
Comments
Espen Harlinn 21-Mar-11 5:08am    
Good tips , 5!
Sergey Alexandrovich Kryukov 21-Mar-11 5:20am    
Thank you, Espen.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900