Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 5936993
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 22, 20262026-05-22T15:28:36+00:00 2026-05-22T15:28:36+00:00

I’m experiencing an issue managing threads on .Net 4.0 C#, and my knowledge of

  • 0

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 = new
    

    Thread(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);

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-22T15:28:37+00:00Added an answer on May 22, 2026 at 3:28 pm

    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.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

No related questions found

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.