简体   繁体   中英

Threadpool or TPL for a long running tasks

I have a windows service which sends out emails after a lengthy process. This service keep on fetching email data from DB table, whenever there is a table entry and process it and will send it out.

Currently it is a multi thread application where we configure Thread count up to 25 in production server(which is solely for this purpose) as this is meant to run 24x7x365 . But we see only 2 active threads running. What could be the reason?

Also I wish to change the threading code here 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);
        }
    }

The reason for why you don't see 25 threads is probably that the thread method, SendEmail , could exit when the thread changes state. Once it exits, the thread is gone and cannot be resumed.

I think you might want to use a different condition on that while loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM