2009-08-25 77 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

相关问题