代码改变世界

【C#】Visual Studio 2017 一边Debug,一边修改代码

  GarfieldEr007  阅读(4167)  评论(0编辑  收藏  举报

好久没写C#了,最近在学习著名科学上网工具 shadowsocks-windows 的源代码,想着可以边断点调试,边加上一些注释以方便理解,stackoverflow 和 msdn 随便翻了一下,竟发现了Debug新世界

一. 原始需求

原始需求是这样,本来我只是希望在断点调试项目的时候,可以增加一些注释,以方便理解。

但是遇到一个问题:
在处于断点模式(Break Mode,即程序当前命中了断点,并在断点处阻塞着不能向下执行)时,是可以随意增加注释的:

当不处于命中断点的状态时(Debug Mode, 程序正在跑呀跑呀跑~),如果我尝试增加注释,就会有这样的提示Changes are not allowed while code is running

有小伙伴说可以用Bookmark,试了一下也不知道是怎么玩的。

之前在XCode中写Objective-C Debug时,注释都是可以随便加的,无论是否处于 Debug Mode 下或处于Break Mode(当前命中了断点)!

二.惊喜的发现

随便逛逛 stackoverflow 和 Microsoft blog,惊喜的发现,原来早在Visual Studio 2013,就可以在断点模式(Break Mode)下增加注释,而且,还可以修改代码,编译器和根据你修改的代码实时改变代码运行过程中的流程(see here)。

举个例子就可以清晰地明白:

以下是一个基于MVC5的Web Application,此时根据变量a的值决定是否进入if内部,显而易见,这时候肯定是会进入if内部的:

现在,我将if(a) 修改为 if(b)(这时候编译器会根据代码的修改,立刻编译),并且step into往下走,竟然发现,我可以实时的改变代码,且改变代码的执行流(修改后,不满足if的条件,因此不会return Content("ss"))。

在之前的使用中,如果我发现这里的判断条件需要修改,且我仍然需要动态调试,我会Stop debugging(Shift + F5),将if(a) 修改为 if(b)Start Debugging,最终代码断点执行到这个位置。

三.如何开启Edit and Continue

Visual Studio 2013开始,这一功能是默认开启的。当然我现在用的是Visual Studio 2017啦,爽爽哒。

如果你发现这个功能不能使用,你需要在你的ProjectVisual Studio中分别检查是否正确设置了:

1.检查在Project中是否开启了这一功能:

对于Web Application是可以在Project中手动开启和关闭的(在 WinForm 的 Project 中好像我没有找到设置):

2.检查在Visual Studio中是否开启了这一功能:

  • [Tools / Options]

  • 搜索Enable Edit and Continue,并勾选

四.一些不能使用的场景

官方指出有些场景下是明确不能使用的, From msdn

  • Mixed-mode (native/managed) debugging.
  • SQL debugging.
  • Debugging a Dr. Watson dump.
  • Editing code after an unhandled exception, when the Unwind the call stack on unhandled exceptions option is not selected.
  • Debugging an embedded runtime application.
  • Debugging an application with Attach to rather than running the application with Start from the Debug menu.
  • Debugging optimized code.
  • Debugging managed code when the target is a 64-bit application. If you want to use Edit and Continue, you must set the target to x86. (ProjectProperties, Compile tab, Advanced Compiler setting.).

别人踩的坑,mark 一下:
Edit and Continue: “Changes are not allowed when the debugger has been attached to an already running process or the code being debugged was optimized at build or run time”

五.参考

努力加载评论中...
点击右上角即可分享
微信分享提示