【问题标题】:On starting a windows service, start threading. How can I accomplish this?在启动 Windows 服务时,启动线程。我怎样才能做到这一点?
【发布时间】:2014-10-28 18:33:49
【问题描述】:

我正在创建一个窗口服务,但是当它启动时,我希望它创建线程来保持 ftp 站点的池/监视器。我面临的问题是,当我尝试使用 while(true){} 在其中检查新文件然后它应该 ThreadPool.QueueUserWorkItem 启动服务时,服务启动时出现超时问题。

【问题讨论】:

  • 你能提供一些你想要做什么的示例代码吗?
  • 这可以作为控制台应用程序完成,通过 Windows 调度程序按计划运行吗?
  • 您的while (true) 循环在哪里?您的服务的“开始”方法需要立即返回,因此在该方法中设置无限循环当然是个坏主意。正如 DVK 指出的那样,没有代码,很难评论您的代码有什么问题。
  • 请分享您的代码。通常,您应该只对 OnStart 事件处理程序执行设置/初始化。您可以从 OnStart 启动多个线程,但您不想在无限循环中执行某些操作。

标签: c# multithreading windows-services threadpool


【解决方案1】:

服务 OnStart 方法中不应有无限 while 循环。该方法应尽快完成。用它来设置服务线程/任务,但不要做任何会无限期阻塞的事情。

没有任何异常处理,线程池等,这就是我以前的做法(上次我写了这样一个线程服务,那是 5 年前,所以如果它过时了,请不要道歉。现在我尝试使用Task Parallel lib),请注意:我只是在演示这个想法,并从一个旧项目中获得了这个。如果您可以做得更好,请随时编辑以改进此答案,或添加您自己的答案。

public partial class GyrasoftMessagingService : ServiceBase
{

  protected override void OnStart(string[] args)
  {
     ThreadStart start = new ThreadStart(FaxWorker); // FaxWorker is where the work gets done
     Thread faxWorkerThread = new Thread(start);

     // set flag to indicate worker thread is active
     serviceStarted = true;

     // start threads
     faxWorkerThread.Start();
  }

  protected override void OnStop()
  {
     serviceStarted = false;
     // wait for threads to stop
     faxWorkerThread.Join(60);

     try
     {
        string error = "";
        Messaging.SMS.SendSMSTextAsync("5555555555", "Messaging Service stopped on " + System.Net.Dns.GetHostName(), ref error);
     }
     catch
     {
        // yes eat exception if text failed
     }
  }

  private static void FaxWorker()
  {
     // loop, poll and do work
  }


}

【讨论】:

    猜你喜欢
    • 2022-11-09
    • 2012-02-16
    • 1970-01-01
    • 1970-01-01
    • 2016-03-12
    • 2018-10-05
    • 1970-01-01
    • 2012-08-18
    • 1970-01-01
    相关资源
    最近更新 更多