【问题标题】:windows service application installationwindows服务应用程序安装
【发布时间】:2012-10-11 16:30:10
【问题描述】:

我是 .NET 的初学者。

我有一个关于运行多线程的 Windows 服务应用程序的问题。我的问题是,当我尝试将我的应用程序注册到 Windows 服务中时,我在服务窗口中的“正在启动”中看到了我的服务状态。我已经包含了几行代码来显示我正在尝试做的事情。

protected override void OnStart(string [] args) {
    timer = Timer(5000);
    timer.Elapsed += new ElapsedEventHandler(OnElapsedTime); 
    timer.Start();

    // when I commented out Application.Run() it runs perfect.
    Application.Run(); // run until all the threads finished working
    //todo
}

private void OnElapsedTime(object s, ElapsedEventArgs e) {
    SmartThreadPool smartThreadPool = new SmartThreadPool();

    while( i < numOfRecords){
         smartThreadPool.QueueWorkItem(DoWork);
         //.....
    }
}

如果您需要更多信息,请告诉我。

【问题讨论】:

  • 您认为Application.Run() 在您提供的上下文中会做什么?
  • 感谢您查看我的代码。对不起,我忘了把循环放在 smartThreadPool.QueueWorkItem(DoWork) 之前。但是我试图在主程序退出之前等待所有正在运行的线程。我希望你明白我想要做什么。让我给你改一下代码。
  • 要让服务显示“已启动”,必须允许 OnStart 完成。以后状态更改还有其他入口点(OnStop 等)。

标签: c# multithreading windows-services


【解决方案1】:

Application.Run() 在您使用的上下文中,它只是告诉服务在同一应用程序上下文中再次运行自己。作为 Windows 服务的一部分,应用程序上下文已经存在于您的 ServiceBase 的上下文中。由于它是一项服务,因此在通过需要它的方法、未处理的异常或外部命令给出停止指令之前,它不会停止。

如果您担心线程在执行过程中不会发生停止,您将需要某种全局锁来指示进程正在工作。这可能就像提升SmartThreadPool 的范围一样简单:

private SmartThreadPool _pool = null;
private SmartThreadPool Pool 
{
    get
    {
        if (_pool == null)
            _pool = new SmartThreadPool();
        return _pool;
    }
}

protected override void OnStop()
{
   if (Pool != null)
   {
       // Forces all threads to finish and 
       // achieve an idle state before 
       // shutting down
       Pool.WaitForIdle();
       Pool.Shutdown();
   }
}

【讨论】:

  • 这正是我要找的。谢谢。在结束这个话题之前,让我问你一个问题。有没有其他方法不使用 WaitForIdle 或 waitforany 方法。
  • @Lakhae:我没有深入研究 SmartThreadPool 类(我假设您使用的是 CodeProject 中的那个),但我确实看到了一个看起来像的方法强制正常关机。我不记得那是什么了。
猜你喜欢
  • 2013-04-02
  • 1970-01-01
  • 2013-08-14
  • 1970-01-01
  • 2013-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多