繁体   English   中英

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

[英]Threadpool or TPL for a long running tasks

我有一个Windows服务,经过漫长的过程后发送电子邮件。 只要有表条目并处理它并将其发送出去,此服务就会继续从数据库表中获取电子邮件数据。

目前它是一个多线程应用程序,我们在生产服务器中配置最多25个线程计数(仅用于此目的),因为这意味着24x7x365运行。 但我们看到只有2个活动线程在运行。 可能是什么原因?

此外,我希望使用线程池或TPL更改线程代码。 你能否建议我一个更好的方法来处理这种情况?

提前致谢 !

//下面的示例代码

    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);
        }
    }

你没有看到25个线程的原因可能是当线程改变状态时线程方法SendEmail可能会退出。 一旦退出,线程就会消失,无法恢复。

我想你可能想在while循环中使用不同的条件。

暂无
暂无

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

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