[英]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.