我得到"此时服务无法接受控制消息"当试图停止服务时。我真的不明白为什么会这样。有人可以帮我弄这个吗?我以为我的锁会阻止这个。
Patrol方法大约需要30-40秒才能运行。
private static readonly string ConnectionString = ConfigurationManager.AppSettings["ConnectionString"];
private static readonly int runMinInterval = Convert.ToInt32(ConfigurationManager.AppSettings["RunMinInterval"]);
private Object myLock = new Object();
private Timer timer;
public DealWatchdogService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
Watchdog.Patrol(ConnectionString, new DealWatchdogService());
timer = new Timer();
timer.Enabled = true;
timer.Interval = 60000 * runMinInterval;
timer.AutoReset = false;
timer.Start();
timer.Elapsed += timer_Elapsed;
}
protected override void OnStop()
{
lock (myLock)
{
timer.Stop();
timer = null;
base.OnStop();
}
}
private void timer_Elapsed(object sender, ElapsedEventArgs e)
{
lock (myLock)
{
if (timer == null)
return;
Watchdog.Patrol(tycheConnection, new DealWatchdogService());
timer.Start();
}
}
编辑:也许有些帮助,但服务有时会停止运行,但是当它启动并运行一周左右时,我就会收到错误。
答案 0 :(得分:1)
Patrol方法大约需要30-40秒才能运行。
我认为问题可能是OnStart()花了太长时间,因为Patrol的长度已经完成,并且正在设置一个标志,表明系统已被锁定。将您的启动代码放到后台线程中,以便OnStart可以更快地完成。
protected override void OnStart(string[] args)
{
//This line does not block.
Task.Run(() => RealStart());
}
private void RealStart()
{
Watchdog.Patrol(ConnectionString, new DealWatchdogService());
timer = new Timer();
//timer.Enabled = true; //Calling .Start() has the same effect.
timer.Interval = 60000 * runMinInterval;
timer.AutoReset = false;
timer.Elapsed += timer_Elapsed;
timer.Start(); //Start should be called after you have set .Elapsed
}
唯一可能的是timer_Elapsed
内部出现问题,但你从未向我们展示过该代码正在做什么。