2013-02-19 152 views
1

我有一个Web服务,我需要确保将完成处理,然后在onstop()被调用时退出。目前当onstop()被调用时,服务立即停止。我被告知查看ManualResetEvent和requeststop标志。我到处找例子甚至发现其中的几个:使用ManualResetEvent检查服务是否已完成处理

How do I safely stop a C# .NET thread running in a Windows service?

To make a choice between ManualResetEvent or Thread.Sleep()

http://www.codeproject.com/Articles/19370/Windows-Services-Made-Simple

但我有这么多的麻烦认识我最能适用于哪一个我情况。下面

代码:

 System.Timers.Timer timer = new System.Timers.Timer(); 
     private volatile bool _requestStop = false; 
     private static readonly string connStr = ConfigurationManager.ConnectionStrings["bedbankstandssConnectionString"].ConnectionString; 
     private readonly ManualResetEvent _allDoneEvt = new ManualResetEvent(true); 
     public InvService() 
     { 
      InitializeComponent(); 
     } 

     protected override void OnStart(string[] args) 
     { 
      _requestStop = false; 
      timer.Elapsed += timer_Elapsed; 
      double pollingInterval = Convert.ToDouble(ConfigurationManager.AppSettings["PollingInterval"]); 
      timer.Interval = pollingInterval; 
      timer.Enabled = true; 
      timer.Start();  
     } 

     protected override void OnStop() 
     { 
      _requestStop = true; 
      timer.Dispose(); 
     } 

     protected override void OnContinue() 
     { } 

     protected override void OnPause() 
     { } 

     private void timer_Elapsed(object sender, EventArgs e) 
     { 
      if (!_requestStop) 
      { 
       timer.Start(); 
       InvProcessingChanges();  
      }    
     } 

     private void InvProcessingChanges() 
     { 
      //Processes changes to inventory 
     } 

是否有人在经历了Windows服务还有谁可以帮我? 刚刚完成我的第一个工作服务的Windows服务我很新。此服务需要在实际停止之前完成库存更新。

回答

3

您使用类似ManualResetEvent的东西等到事件进入信号状态,然后再完成StopManualResetEventSlim可能更适合考虑您尝试在同一过程中发出信号。

基本上,您可以在停止期间以及在您处理呼叫Reset时拨打电话Wait,当您完成时,请致电Set

例如

private ManualResetEventSlim resetEvent = new ManualResetEventSlim(false); 

public void InvProcessingChanges() 
{ 
    resetEventSlim.Reset(); 
    try 
    { 
     // TODO: *the* processing 
    } 
    finally 
    { 
     resetEvent.Set(); 
    } 
} 

public void WaitUntilProcessingComplete() 
{ 
    resetEvent.Wait(); 
} 

,并根据您的服务:

protected override void OnStop() 
    { 
     WaitUntilProcessingComplete(); 
    } 
+0

只是一个问题@peter是你WebServiceProcessMethod我invprocessingchanges? – user1270384 2013-02-19 20:49:55

+0

@ user1270384是的,我编辑了答案来反映这一点。 – 2013-02-19 22:01:26

+0

请注意我的Onstop如何具有以下代码protected override void OnStop() { _requestStop = true; timer.Dispose(); }它现在改变了还是你的代码被包含在这? – user1270384 2013-02-19 22:26:44

相关问题