I’m experiencing an issue managing threads on .Net 4.0 C#, and my knowledge of threads is not sufficient to solve it, so I’ve post it here expecting that somebody could give me some piece of advise please.
The scenario is the following:
We have a Windows service on C# framework 4.0 that (1)connects via socket to a server to get a .PCM file, (2)then convert it to a .WAV file, (3)send it via Email – SMTP and finally (4)notify the initial server that it was successfully sent.
The server where the service had been installed has 8 processors and 8 GB or RAM.
To allow multiprocessing I’ve built the service with 4 threads, each one of them performs each task I mentioned previously.
On the code, I have classes and methods for each task, so I create threads and invoke methods as follows:
Thread eachThread = new Thread(object.PerformTask);
Inside each method I’m having a While that checks if the connection of the socket is alive and continue fetching data or processing data depending on their porpuse.
while (_socket.Connected){
//perform task
}
The problem is that as more services are being installed (the same windows service is replicated and pointed between two endpoints on the server to get the files via socket) the CPU consumption increases dramatically, each service continues running and processing files but there is a moment were the CPU consumption is too high that the server just collapse.
The question is: what would you suggest me to handle this scenario, I mean in general terms what could be a good approach of handling this highly demanded processing tasks to avoid the server to collapse in CPU consumption?
Thanks.
PS.: If anybody needs more details on the scenario, please let me know.
Edit 1
With CPU collapse I mean that the server gets too slow that we have to restart it.
Edit 2
Here I post some part of the code so you can get an idea of how it’s programmed:
while(true){
//starting the service
try
{
IPEndPoint endPoint = conn.SettingConnection();
string id = _objProp.Parametros.IdApp;
using (socket = conn.Connect(endPoint))
{
while (!socket.Connected)
{
_log.SetLog("INFO", "Conectando socket...");
socket = conn.Connect(endPoint);
//if the connection failed, wait 5 seconds for a new try.
if (!socket.Connected)
{
Thread.Sleep(5000);
}
}
proInThread = new Thread(proIn.ThreadRun);
conInThread = new Thread(conIn.ThreadRun);
conOutThread = new Thread(conOut.ThreadRun);
proInThread.Start();
conInThread.Start();
conOutThread.Start();
proInThread.Join();
conInThread.Join();
conOutThread.Join();
}
}
}
Edit 3
-
Thread 1
while (_socket.Connected)
{
try
{
var conn = new AppConection(ref _objPropiedades);try { string message = conn.ReceiveMessage(_socket); lock (((ICollection)_queue).SyncRoot) { _queue.Enqueue(message); _syncEvents.NewItemEvent.Set(); _syncEvents.NewResetEvent.Set(); } lock (((ICollection)_total_rec).SyncRoot) { _total_rec.Add("1"); } } catch (SocketException ex) { //log exception } catch (IndexOutOfRangeException ex) { //log exception } catch (Exception ex) { //log exception } //message received } catch (Exception ex) { //logging error } } //release ANY instance that could be using memory _socket.Dispose(); log = null; -
Thread 2
while (_socket.Connected)
{
try{
_syncEvents.NewItemEventOut.WaitOne();if (_socket.Connected) { lock (((ICollection)_queue).SyncRoot) { total_queue = _queue.Count(); } int i = 0; while (i < total_queue) { //EMail Emails; string mail = ""; lock (((ICollection)_queue).SyncRoot) { mail = _queue.Dequeue(); i = i + 1; } try { conn.SendMessage(_socket, mail); _syncEvents.NewResetEvent.Set(); } catch (SocketException ex) { //log exception } } } else { //log exception _syncEvents.NewAbortEvent.Set(); Thread.CurrentThread.Abort(); } } catch (InvalidOperationException e) { //log exception } catch (Exception e) { //log exception } } //release ANY instance that could be using memory _socket.Dispose(); conn = null; log = null; -
Thread 3
while (_socket.Connected)
{int total_queue = 0; try { _syncEvents.NewItemEvent.WaitOne(); lock (((ICollection) _queue).SyncRoot) { total_queue = _queue.Count(); } int i = 0; while (i < total_queue) { if (mgthreads.GetThreatdAct() <mgthreads.GetMaxThread())
{
string message = “”;
lock (((ICollection) _queue).SyncRoot)
{message = _queue.Dequeue(); i = i + 1; } count++; lock (((ICollection) _queueO).SyncRoot) { app.SetParameters(_socket, _id,message, _queueO, _syncEvents,
_total_Env, _total_err);
}Thread producerThread = newThread(app.ThreadJob) { Name =
“ProducerThread_” +
DateTime.Now.ToString(“ddMMyyyyhhmmss”),
Priority = ThreadPriority.AboveNormal
};
producerThread.Start();producerThread.Join(); mgthreads.IncThreatdAct(producerThread); } mgthreads.DecThreatdAct(); } mgthreads.DecThreatdAct(); } catch (InvalidOperationException e) { } catch (Exception e) { } Thread.Sleep(500); } //release ANY instance that could be using memory _socket.Dispose(); app = null; log = null; mgthreads = null; -
Thread 4
MessageVO mesVo =
fac.ParseMessageXml(_message);
I would lower the thread priority and have all threads pass through a Semaphore that limits concurrency to Environment.ProcessorCount. This not a perfect solution but it sounds like it is enough in this case and an easy fix.
Edit: Thinking about it, you have to fold the 10 services into one single process because otherwise you won’t have centralized control about the threads that are running. If you have 10 independent processes they cannot coordinate.