各位好!
我现在有一个问题想向大家请教下,具体内容如下:
我在网站程序的Global.asax文件的Application_Start事件中启用了一个新的线程,这个线程的作用就是每隔固定的时间,例如30秒,就会自动从POP3服务器接收并进行相应的处理,当网站部署后,是不是有客户端访问这个网站时线程就会自动启动(当然是启动一次)。现在的问题是:这个线程启动后会停止吗?例如,如果长时间没有客户端请求,还有我如果想手动停止它的话该怎么做呢?我启动的线程的代码大致如下:
public void StartReceiveEmailsFromPOP3Server()
        {
object[] parameters = new object[] { HttpContext.Current };
            ParameterizedThreadStart pts = new ParameterizedThreadStart(ReceiveEmails);
            Thread thread = new Thread(pts);
            thread.Name = "ReceiveEmails";
            thread.Priority = ThreadPriority.BelowNormal;
            thread.Start(parameters);

ReceiveEmails是一个循环从POP3服务器获取邮件并处理的程序
Application_Start方法中会调用StartReceiveEmailsFromPOP3Server这个方法。这个问题比较重要,我现在考虑是使用windows服务还是在网站程序中使用线程,在此先谢谢各位了!

解决方案 »

  1.   

    定义全局的定时器
         public class Global : System.Web.HttpApplication
        {
            public static Timer gtimer = null; // 定义全局定时器类对象        protected void Application_Start(object sender, EventArgs e)
            {
                gtimer = new Timer(1000000); //16.7分钟执行一次方法
                // 将自定义用户函数(TimerEventFunction)指定为计时器的 Elapsed 事件处理程序
                // TimerEventFunction 可以写入自己的需要执行的代码逻辑
                gtimer.Elapsed += new System.Timers.ElapsedEventHandler(this.TimerEventFunction);
                // AutoReset 属性为 true 时,每隔指定时间间隔触发一次事件
                // 若赋值 false,则只执行一次
                gtimer.AutoReset = true;
                gtimer.Enabled = true;        }
            protected void TimerEventFunction(Object sender, ElapsedEventArgs e)
            {
               //触发事件,相应的操作!
            }
        }
     
      

  2.   

    据说时间长了没有访问的情况下会停止的,这种定时的东西最好用window 服务的
      

  3.   

    谢谢二位的解答,最后为了稳定起见还是使用windows服务。