如何配置timer和thread.sleep以便thread.sleep将等到所有代码执行完毕

时间:2016-04-18 22:10:43

标签: c# windows windows-services

我编写了一个小的Windows服务,它将读取由Windows应用程序创建的xml文件并保存到特定位置。 xml文件包含多个开始时间,结束时间和执行时间,我的Windows服务将通过查询sql server数据库来创建excel表。我的问题是在我的代码执行中间调用thread.sleep并且我的代码没有完全执行。

我的program.cs代码:

namespace RepService
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
#if(!DEBUG)
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[] 
            { 
                new Service1() 
            };
            ServiceBase.Run(ServicesToRun);
#else
            Service1 myServ = new Service1();
            myServ.Start();
            //Set the Thread to sleep

            Thread.Sleep(60000);
            //Call the Stop method-this will stop the Timer.
            myServ.Stop();
#endif
        }
    }
}

我的service1.cs文件包含以下代码:

public Service1()
        {
            _aTimer = new System.Timers.Timer(30000);
            _aTimer.Enabled = true;
            _aTimer.Elapsed += new System.Timers.ElapsedEventHandler(_aTimer_Elapsed);
            InitializeComponent();
}
void _aTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {//huge code to be executed
}

如何配置我的计时器和thread.sleep,以便我可以避免因thread.sleep而跳过我的代码执行。我想每15分钟运行一次我的服务。不能按要求使用任务调度程序。

3 个答案:

答案 0 :(得分:0)

在服务方法的回调中执行thread.sleep

答案 1 :(得分:0)

将行Thread.Sleep(60000);替换为await Task.Delay(60000);

答案 2 :(得分:0)

就个人而言,我从不使用Thread.Sleep(),因为你无法快速摆脱它们(比如试图关闭时);我建议将AutoResetEvent用于“睡眠”功能,并使用它们来查看其他代码何时完成。你可以这样做:

public System.Threading.AutoResetEvent doneFlag = new System.Threading.AutoResetEvent(false); // used to signal when other work is done

....

Service1 myServ = new Service1();
myServ.Start();
if(doneFlag.WaitOne(SOME_TIMEOUT))
{
    // doneFlag was set, so other code finished executing
}
else
{
    // doneFlag was not set, SOME_TIMEOUT time was exceeded. Do whatever you want to handle that here
}
....
void _aTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
    //huge code to be executed
    doneFlag.Set(); // this will trigger the previous code pretty much immediately to continue
}

希望这就是你要找的东西。如果您有任何问题,请告诉我们!

PS:我不确定是谁继续评价问题。特别是因为没有解释为什么有人投了票。人们应该尝试更多的帮助,而不仅仅是一个混蛋,然后跑掉。评价它来反击行动......

相关问题