2014-10-28 16 views
1

我正在創建一個窗口服務,但是當它啓動時,我希望它創建線程來保持ftp站點的池/監視器。我面臨的問題是當我嘗試啓動服務時,(true){}其中檢查新文件,然後它應該ThreadPool.QueueUserWorkItem,該服務在啓動時有超時問題。在啓動Windows服務時,請啓動線程。我怎樣才能做到這一點?

+1

你能提供一些你正在嘗試做的例子嗎? – DVK 2014-10-28 18:37:47

+0

這可以作爲一個控制檯應用程序完成,通過Windows調度程序按計劃運行? – 2014-10-28 18:39:20

+0

你在哪裏有'while(true)'循環?你的服務的「開始」方法需要立即返回,所以當然在該方法中放入一個無限循環將是一個壞主意。正如DVK指出的那樣,如果沒有代碼,就很難評論代碼的問題。 – 2014-10-28 18:50:31

回答

4

服務OnStart方法中應該沒有無限循環。該方法應儘快完成。使用它來設置服務線程/任務,但不要做任何會無限期阻塞的事情。如果沒有任何異常處理,線程池等,這裏就是我以前的做法(上次我寫了這樣一個線程服務,這是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 
    } 


} 
相關問題