2009-11-12 198 views
0

我的Windows服務能夠在Win XP中啓動線程(啓動ThreadStart委託),但在Win 2003 Server中它不能,它也不會引發異常...線程根本無法啓動。Windows服務無法啓動Win 2003服務器中的線程

我做了一個在(OnStart)事件處理程序中具有相同代碼的測試Windows服務,它在Win XP和Win 2003 Server上工作,這讓我發瘋,我不知道我的原始服務有什麼問題,爲什麼它不能啓動線程。

這裏是我的兩個服務取勝的問題,並在測試服務贏得了代碼工作就好了:

private Thread trd; 
    StreamWriter sw; 
    int i = 0; 


    protected override void OnStart(string[] args) 
    { 
     // TODO: Add code here to start your service. 
     sw = new StreamWriter("c:\\TestingService.txt", true); 

     trd = new Thread(new ThreadStart(this.LoopingThread)); 
     trd.IsBackground = false; 
     trd.Priority = ThreadPriority.Highest; 
     trd.Start(); 
    } 

    protected override void OnStop() 
    { 
     // TODO: Add code here to perform any tear-down necessary to stop your service. 
    } 

    private void LoopingThread() 
    { 
     while (i < 100) 
     { 
      lock (sw) 
      { 
       sw.WriteLine("hello from thread i="+i.ToString()); 
       sw.Flush(); 
      } 
      i++; 
      Thread.Sleep(1000); 
     } 
    } 

這個代碼是在兩個服務取勝「正是」相同。 我原來的服務(有問題)得到了其他DLL多次提到,其「使用」列表是:

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Diagnostics; 
using System.ServiceProcess; 
using System.Text; 
using System.IO; 
using System.Xml; 
using System.Security.Principal; 
using System.Reflection; 
using System.Threading; 
using System.Management; 

和其他using語句是相關的一些機密的DLL(第三方) 但我我實際上並沒有創建任何對象......有效的代碼就是我發佈的內容。

我無法弄清楚,爲什麼我的服務贏得不能在2003年贏得服務器啓動線程

+0

什麼是在事件日誌中爲此?它會給我們更多的線索來幫助你 – AutomatedTester 2009-11-12 08:17:20

+0

我有點困惑 - 你是說你發佈的代碼本身工作正常(在Win2003上),但是當你添加引用到第三方(和其他DLL)和使用語句顯示它停止工作? – 2009-11-12 08:35:46

回答

0

這是以非常愚蠢的方式解決的! 我剛剛在Windows服務中創建了另一個類,將所有代碼複製到它,然後在program.cs中創建代碼,而不是舊服務類的實例。

之後一切正常,我不知道發生了什麼!

感謝所有那些試圖幫助的人

1

在你的OnStart()方法的開頭放至System.Diagnostics.Debugger.Break()的調用,並在調試編譯。當您啓動該服務時,系統會提示您啓動調試會話。進入調試器後,從「調試」菜單中打開「異常」對話框,並查看「拋出」列以瞭解公共語言運行時異常。如果發生異常,您的服務將暫停。

如果我不得不猜測,我會說你的線程沒有啓動的原因是因爲它沒有那麼做。根據您提供的代碼,我會說由於某種原因,StreamWriter的創建失敗。例如,您可能沒有Win 2003 Server計算機上的C驅動器的寫入權限。