c# - Windows服务应用程序安装

标签 c# multithreading windows-services

我是 .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() 在您使用的上下文中,它只是告诉服务在同一应用程序上下文中再次运行自身。作为 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();
   }
}

关于c# - Windows服务应用程序安装,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12844296/

相关文章:

c++ - C++ 中的 Windows 服务

wcf - Windows 服务中托管的 MSMQ 支持的 WCF 服务在启动时失败

c# - TypeScript:相当于 C# 的用于扩展类的通用类型约束?

c# - Linq To SQL - 具有和分组依据

c# - 线程安全的 WebApi 放置请求

python - 使用多重处理以自己的方法映射数组的每个元素

c# - 进度条不工作

c# - 连接超时 VS IIS

Java单线程CPU使用和多线程CPU使用

windows - Windows 服务中是否允许 Windows-GUI 调用(创建可见窗口等)?