Windows 服务未完全启动
我用 C# 创建了这个小型 Windows 服务,我相信我的 ThreadPool 代码可能做错了什么,导致 Windows 服务无法完全启动。如果您必须知道,Windows 服务似乎运行完美,只是当查看服务控制台时,它仍然表明它正在“启动”。当我重新启动服务器时,即使我已将其设置为自动启动,该服务似乎又停止了。
请参阅下面我的代码:
protected override void OnStart(string[] args)
{
int itemCount = itemList.Count;
this.doneEvents = new ManualResetEvent[itemCount];
for (int i = 0; i < itemCount; i++)
{
int oId = this.itemList[i];
this.doneEvents[i] = new ManualResetEvent(false);
ThreadPool.QueueUserWorkItem(data =>
{
while (this.activated)
{
DateTime start = DateTime.Now;
// my code here
// choke point
TimeSpan duration = (DateTime.Now - start);
if (duration.Milliseconds < CONST_WAITMILLISECONDS)
Thread.Sleep((CONST_WAITMILLISECONDS - duration.Milliseconds));
}
this.doneEvents[i].Set(); // thread done
}, oId);
}
WaitHandle.WaitAll(doneEvents);
}
I made this small windows service in c# and I believe I may have done something wrong with my ThreadPool code that prevents my Windows Service from completely starting. If you must know, the windows service seems to be running perfectly only that when looked upon the Services console, it still states that it is "starting". When I restarted my server, the service seem to have stopped again even though I have set it to Automatic startup.
Please see my code below:
protected override void OnStart(string[] args)
{
int itemCount = itemList.Count;
this.doneEvents = new ManualResetEvent[itemCount];
for (int i = 0; i < itemCount; i++)
{
int oId = this.itemList[i];
this.doneEvents[i] = new ManualResetEvent(false);
ThreadPool.QueueUserWorkItem(data =>
{
while (this.activated)
{
DateTime start = DateTime.Now;
// my code here
// choke point
TimeSpan duration = (DateTime.Now - start);
if (duration.Milliseconds < CONST_WAITMILLISECONDS)
Thread.Sleep((CONST_WAITMILLISECONDS - duration.Milliseconds));
}
this.doneEvents[i].Set(); // thread done
}, oId);
}
WaitHandle.WaitAll(doneEvents);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在通过
WaitHandle.WaitAll(doneEvents);
阻止OnStart
调用。 Windows 尝试启动该服务,但由于WaitAll
而超时。如果您希望 Windows 将服务视为已启动,则需要让
OnStart
完成。You are blocking the
OnStart
call byWaitHandle.WaitAll(doneEvents);
. Windows tries to start the service but times out because ofWaitAll
.You need to let
OnStart
complete if you want Windows to treat the service as started.我认为您可以将
OnStart
内的逻辑包装在一个线程中。当您收到OnStop
事件时,该线程将关闭。像这样的东西:
I think you could wrap the logic inside
OnStart
in a thread. This thread would be closed when you received anOnStop
event.Something like this: