我有一個Windows服務,我放在一起從衆多博客和論壇上的,主要是我提出的問題,並在這裏找到答案。該服務工作正常。唯一的問題是當我停止服務時,粘貼進一步是我在停止日誌文件時看到的內容。Windows服務調用OnStop問題
public partial class GBBInvService : ServiceBase
{
private static readonly ILog log = LogManager.GetLogger(typeof(GBBInvService));
System.Timers.Timer timer = new System.Timers.Timer();
private volatile bool _requestStop=false;
private ManualResetEventSlim resetEvent = new ManualResetEventSlim(false);
public GBBInvService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
_requestStop = false;
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
timer.Interval = 18000;
timer.Enabled = true;
timer.Start();
log.Info("GBBInvService Service Started");
}
protected override void OnStop()
{
log.Info("inside stop");
if (!_requestStop)
{
log.Info("Stop not requested");
timer.Start();
}
else
{
log.Info("On Stop Called");
WaitUntilProcessCompleted();
}
}
private void timer_Elapsed(object sender, ElapsedEventArgs e)
{
log.Info("Timer elapsed at " + Convert.ToString(e.SignalTime));
InvProcessing();
}
private void InvProcessing()
{
try
{
resetEvent.Reset();
//*Processing here*
}
catch (Exception ex)
{
resetEvent.Set();
log.Error(ex.Message);
}
}
private void WaitUntilProcessCompleted()
{
resetEvent.Wait();
}
}
服務正常停止並再次開始很好,但我不知道是否我的代碼是錯誤的,因爲日誌文件顯示:
2013年4月23日14:53:01062 [ 6] INFO GBBInvService.GBBInventoryService [(空)] - 內停止
2013年4月23日14:53:01062 [6] INFO GBBInvService.GBBInventoryService [(空)] - 停止未請求
這是怎麼回事的(!_requestStop)
內,而不是else
的。我的代碼錯了嗎?有人能夠向我解釋爲什麼它會進入(!_requestStop)
而不是else語句。
任何意見,將不勝感激,因爲我只是剛剛開始獲得Windows服務和最近日誌記錄的動手。
所以我的代碼是正確的? – user1270384 2013-04-23 03:21:20