2009-08-25 43 views
13

有沒有什麼方法可以檢測調試器在內存中運行?在調試器下運行時更改程序流程

這裏來的表單加載僞代碼。

if debugger.IsRunning then 
Application.exit 
end if 

編輯:原標題被

+1

大多數調試可以安裝在運行時的過程。在這種情況下,在statrup上檢查調試器將無濟於事。 – 2009-08-25 19:40:18

回答

29

「在內存調試檢測的」請嘗試以下

if (System.Diagnostics.Debugger.IsAttached) { 
    ... 
} 
5

有兩件事要記住使用此之前關閉應用程序繼續運行在調試器中:

  1. 我已經使用調試器來拉交流來自商業.NET應用程序的匆匆跟蹤,並將其發送到公司,在那裏它隨後被修復,並感謝您使它變得容易並且
  2. 該檢查可以是平凡失敗。

現在,要多用,這裏是如何使用這種檢測,以保持func eval在調試器來改變你的程序的狀態,如果你有一個緩存性能原因,懶洋洋地評估物業。

private object _calculatedProperty; 

public object SomeCalculatedProperty 
{ 
    get 
    { 
     if (_calculatedProperty == null) 
     { 
      object property = /*calculate property*/; 
      if (System.Diagnostics.Debugger.IsAttached) 
       return property; 

      _calculatedProperty = property; 
     } 

     return _calculatedProperty; 
    } 
} 

我也用這個變體在次,以確保我的調試器步進式不會跳過評價:

private object _calculatedProperty; 

public object SomeCalculatedProperty 
{ 
    get 
    { 
     bool debuggerAttached = System.Diagnostics.Debugger.IsAttached; 

     if (_calculatedProperty == null || debuggerAttached) 
     { 
      object property = /*calculate property*/; 
      if (debuggerAttached) 
       return property; 

      _calculatedProperty = property; 
     } 

     return _calculatedProperty; 
    } 
} 
+0

這是一個很酷的想法 - 但它在調試器下運行時會改變程序的流程,所以您不再調試您在發行版中使用的代碼。恕我直言,在大多數情況下,提供一個屬性的非緩存變體(在#if DEBUG中,所以它沒有內置到發行版中),可以在調試器中使用它來檢查值,從而使「真實」屬性工作在調試和發佈版本中都是一樣的。 – 2009-08-25 20:01:28

+0

@Jason:是的,沒有。在這種情況下,所有被調用來評估屬性的方法都是純粹的(無論何時調用都不會產生副作用),所以我確實確保從應用程序的角度來看,這也適用於屬性。 – 2009-08-25 20:20:34

相關問題