好久沒寫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
啦,爽爽噠。
如果你發現這個功能不能使用,你需要在你的Project
和Visual 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.).
五.參考
- How to: Enable and Disable Edit and Continue
- Changes are not allowed when the debugger
- Supported Code Changes (C#)
- https://msdn.microsoft.com/en-us/library/7932e88z.aspx
- from:http://swsmile.info/2017/04/03/%E3%80%90C-%E3%80%91Visual-Studio-2017-%E4%B8%80%E8%BE%B9Debug%EF%BC%8C%E4%B8%80%E8%BE%B9%E4%BF%AE%E6%94%B9%E4%BB%A3%E7%A0%81/