簡體   English   中英

Debug.WriteLine() 未命中

[英]Debug.WriteLine() is not hit

我正在使用以下代碼調試 Windows 服務(通過在 Visual Studio 2010 中按F5 ):

Program.cs文件中:

static void Main() {

    if (!Environment.UserInteractive) {
        // We are not in debug mode, startup as service

        ServiceBase[] ServicesToRun;
        ServicesToRun = new ServiceBase[] { new MyServer() };
        ServiceBase.Run(ServicesToRun);
    } 
    else {
        // We are in debug mode, startup as application

        MyServer service = new MyServer();
        service.StartService();
        System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
    }
}

MyServer.cs文件中:

public void StartService() {
    this.OnStart(new string[0]);
}

過去,我在所有服務代碼中使用Debug.WriteLine("xxx")行沒有任何問題,但現在我注意到不再調用所有Debug.WriteLine()行。

當我使用Step Into ( F11 ) 進行調試時,我清楚地看到調試器正在跳過這些行 - (因此,output 窗口上沒有 output 文本),而服務在“調試模式”下正確啟動。

我不明白為什么不會調用Debug代碼。 建議?

我在調試模式下構建我的解決方案(檢查了Define DEBUG constant ),但我注意到沒有調用#if DEBUG... #endif包圍的代碼。 這很奇怪……

似乎缺少調試符號。

  1. 清理您的解決方案,重新啟動 Visual Studio,重新構建解決方案。
  2. 確保配置管理器處於調試模式。
  3. 檢查工具>選項>調試並取消選中“僅啟用我的代碼”

發生在我身上,這似乎有幫助。

我有同樣的隨機問題。

我能夠通過以下方式修復它:

  1. 取消選中Project Properties -> Build -> Define DEBUG constant
  2. 點擊保存
  3. 再次檢查'Define DEBUG constant'選項
  4. 點擊保存
  5. 重建項目

這樣做之后,它按預期命中了#if DEBUG行。

如果您不使用調試版本,則編譯器會排除代碼。 該方法的簽名類似於:

[Conditional("DEBUG")]
public static void WriteLine(string message) { }

當您進行調試構建時,該屬性告訴編譯器包含對相關方法的調用 因此,如果您沒有使用 DEBUG 標志集進行編譯(例如,發布版本),那么編譯器將完全放棄調用。

Debug.Assert也是如此。

您也可以在自己的代碼中使用此屬性,以及您喜歡的任何 label。

考慮此屬性的另一種方式是,它強制對具有該屬性的方法的所有調用都包含在指令中——例如:

    DoSomething();

#if DEBUG
    Debug.WriteLine("I'm a debug build");
#endif

    DoSomethingElse();

編輯

你想通過Environment.UserInteractive實現什么? 也許您的意思是Debugger.IsAttached 如果您想檢查它是否是調試版本,那么您可以使用上面的ConditionalAttribute#if #endif指令。

Environment.UserInteractive與調試模式不同——這只是意味着您在控制台中運行它而不是作為服務運行。 確保您的構建配置設置為調試。

導航到 Project Properties -> Build 並確保選中“Define DEBUG Constant”和“Define TRACE Constant”復選框。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM