启动Windows服务时,启动线程.我怎么能做到这一点?

Nat*_*ion 1 c# multithreading windows-services threadpool

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

cod*_*eim 6

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

没有任何异常处理,线程池等,这是我以前的做法(上次我写了这样一个线程服务,这是5年前,所以没有道歉,如果它已过时.现在我尝试使用任务并行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
  }


}
Run Code Online (Sandbox Code Playgroud)