![](/img/trans.png)
[英]how to configure timer and thread.sleep so that thread.sleep will wait until all the code is executed
[英]Sleep windows service until Thread timer starts
我正在創建一個Windows服務來運行一些間隔的任務。 在這里,用戶可以設置任務開始時間(第一次運行)和任務間隔。 在OnStart
事件的程序中,設置計時器並等待觸發器。
但問題是線程計時器啟動前主線程死了。 所以我嘗試添加Thread.CurrentThread.Join()
和Sleep()
直到計時器啟動。 但在我安裝Windows服務后,我無法啟動Windows服務,因為sleep
或block
是在OnStart
事件中。 所以它卡住了,或者睡了很長時間並且顯示出一些異常。
我只需要停止退出主線程直到線程定時器觸發器。
public partial class Service1 : ServiceBase
{
TimerCallback timer_delegate;
Timer houskeep_timer;
protected override void OnStart(string[] args)
{
SettingReader settings = new SettingReader();
if (settings.init())
{
timer_delegate = new TimerCallback(houseKeep);
houskeep_timer = new Timer(timer_delegate, "testing", 33333100000, 44450000);
//Thread.CurrentThread.Join();
}
}
private void houseKeep(object setting_obj)
{
string message = (string)setting_obj;
writeToLogFile(message);
}
}
我不會使用計時器,我會使用普通的exe並在任務調度程序中設置它。 否則,您只是實現自己的調度,而內置於Windows中的功能要少得多。
請參閱Jon Galloway的帖子 ,了解為何不使用服務來運行計划任務。
請注意,這不是執行多線程處理的最佳方法,但它可能是解決您的問題的方法。
使用一個對於踏板是全局的布爾變量。 將它設置在主踏板上,看它是否發生變化! 當您希望主線程退出時,在服務步驟中更改它。 之后主線程將在您想要的時間退出。 只要您在踏板之間創建的標志是bool
就不需要執行任何invoke
方法或其他操作。
這將實現您的需求
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
namespace WindowsService1
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
private System.Threading.AutoResetEvent are = new System.Threading.AutoResetEvent(false);
protected override void OnStart(string[] args)
{
new System.Threading.Thread(mt) { IsBackground = true }.Start();
}
private void mt()
{
// Set up timer here
// wait for OnStop indefinitely
are.WaitOne();
}
protected override void OnStop()
{
are.Set();
}
}
}
OnStart將啟動一個無限期等待OnStop的線程。 在這個帖子中,您將創建您的計時器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.