繁体   English   中英

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

[英]how to configure timer and thread.sleep so that thread.sleep will wait until all the code is executed

我已经编写了一个小型Windows服务,该服务将读取Windows应用程序创建的xml文件并保存到特定位置。 xml文件包含多个开始时间,结束时间和执行时间,根据这些时间,我的Windows服务将通过查询sql server数据库来创建Excel工作表。 我的问题在代码执行线程中间.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分钟运行一次我的服务。 不能根据要求使用任务计划程序。

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

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

就我个人而言,我从不使用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:我不确定谁会继续评价问题。 特别是因为实际上没有任何关于为什么有人拒绝的解释。人们应该尝试的不仅是成为一个混蛋,然后逃跑,还应该提供更多帮助。

暂无
暂无

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

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