Threadpool or TPL for long running tasks

I have a windows service that sends emails after a lengthy process. This service continues to receive email data from the DB table whenever there is a record in the table and processes it and sends it.

This is currently a multi-thread application in which we will configure the Thread to 25 on the production server (which is solely for this purpose) as it is designed to run 24x7x365. But we only see 2 active threads. What could be the reason?

Also I want to change my thread code using thread pool or TPL. Could you please suggest me a better way to handle this scenario?

Thanks in advance!

// Sample code below

    Thread[] threads;
    int ThreadCount = 25;
    private void StartProcess()
    {
        //Create new threads 
        if (Threads == null)
        {
            // Create array of threads based on the configuration
            threads = new Thread[ThreadCount];
            for (int i = 0; i < ThreadCount; i++)
            {
                Thread[] threads[i] = new Thread(new ThreadStart(SendEmail));
                threads[i].Start();
            }
        }
        else
        {
            resume it if exists
            for (int j = 0; j < threads.Length; j++)
            {
                if (threads[j].ThreadState == Threading.ThreadState.Suspended)
                {                        
                    threads[j].Resume();
                }
            }
        }
    }
   public void SendEmail()
    {
        while (Thread.CurrentThread.ThreadState == System.Threading.ThreadState.Running)
        {
              // send email code
            Thread.Sleep(duration);
        }
    }

      

+3


source to share


1 answer


The reason why you don't see 25 threads is likely that the thread method SendEmail

might exit when the thread changes state. When it exits, the thread will disappear and cannot be resumed.



I think you can use a different condition for this loop while

.

0


source







All Articles