Click here to Skip to main content
15,892,643 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi
I have a .NET application that communicates with a hardware device by TCP/IP. The hardware device acts as a server and disconnect after after 5 seconds with no communication. If the device receives a Scan-command (to see if the device is online) it will disconnect just after sending the answer back to my application. My application has to scan for available devices. This means that I have to make a new Socket connection each time I Scan. After maybe 10 hours I get an OutOfMemory exception. My application only uses about 160MB when I get this exception and CPU usage is close to 0% but the number og threads in my application is more than 1000 (according to Windows Task Manager). I only span about 2 threads so maybe .NET is spanning a lot of threads each time I have to make a new Socket connection? I assume that the OutOfMemory exception has to do with the big number of threads in the process.

I periodically do like this every 4th second:
1) Try to send a Scan command. This gives a Socket exception since the device always will close the connection after a Scan command. (If it was a none-scan command the connection would maybe stay open but I use the Socket exception to test if I must make a new connection. The Socket.Connected property only show if there was a connection the LAST time).
2) When getting this Socket exception I will make a new connection like this:

C#
private Socket _clientSock;

//Close all used recources (but this does not help??!)         
if (_clientSock != null)
{
   this._clientSock.Shutdown(SocketShutdown.Both);
   this._clientSock.Close();
   this._clientSock = null;

   System.Threading.Thread.Sleep(300);
}

this._clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
this._clientSock.Connect(_IP, _port);

//Send the command after reconnecting
_bytes = this._clientSock.Send(this._byteListFromPC.ToArray());


3) Then I have a new connection and I get the correct answer from the device
4) Then I repeat 1) to 3) because I must always know when the device is online and ready for real use.
Posted
Comments
Richard MacCutchan 30-Mar-15 3:54am    
I would guess that the problem lies elsewhere in your code where you are creating the threads.

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