ASP.NET Threads和Static类

时间:2012-03-07 18:02:36

标签: asp.net multithreading thread-safety

我创建了Scheduler类,在启动ASP.NET应用程序时调用MailBot.Start静态方法。我怀疑代码不是线程安全的,因为MailBot.Start方法中的某些变量(可能不确定)是混合的。这是真的吗? 我希望整个ASP.NET应用程序只有一个方法running

void Application_Start(object sender, EventArgs e)
{

    WebHelper.Scheduler(TimeSpan.FromMinutes(2), TimeSpan.FromMinutes(10), MailBot.Start);

}


public static class MailBot
{
    public static void Start()
    {

        //The actual code...

    }
}


     public delegate void SchedulerEvent();

     public static void Scheduler(TimeSpan firstTime, TimeSpan interval, SchedulerEvent callback)
            {
                var timer = new System.Timers.Timer { Interval = firstTime.TotalMilliseconds };
                timer.Elapsed += delegate
                                     {

                                         timer.Enabled = false;
                                         try
                                         {
                                             timer.Interval = interval.TotalMilliseconds;

                                             callback();


                                         }
                                         finally
                                         {
                                             timer.Enabled = true;
                                         }
                                     };
                timer.Start();
            }

0 个答案:

没有答案