简体   繁体   English

Threadpool或TPL用于长时间运行的任务

[英]Threadpool or TPL for a long running tasks

I have a windows service which sends out emails after a lengthy process. 我有一个Windows服务,经过漫长的过程后发送电子邮件。 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 . 目前它是一个多线程应用程序,我们在生产服务器中配置最多25个线程计数(仅用于此目的),因为这意味着24x7x365运行。 But we see only 2 active threads running. 但我们看到只有2个活动线程在运行。 What could be the reason? 可能是什么原因?

Also I wish to change the threading code here using thread pool or TPL. 此外,我希望使用线程池或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. 你没有看到25个线程的原因可能是当线程改变状态时线程方法SendEmail可能会退出。 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. 我想你可能想在while循环中使用不同的条件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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