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