使用Process.Start()由外部程序启动我的代码时进行调试 [英] Debugging when my code is started by external program with Process.Start()
问题描述
假设我有一个C#WinForms应用程序,它是由外部程序通过简单地使用Process.Start(MyModule.exe)
启动的.
Suppose I have a C# WinForms application and it is started by external program simply by using Process.Start(MyModule.exe)
.
我尝试使用我的项目属性-> 调试-> 开始操作-> 开始调试代码外部程序(当然还要设置正确的工作目录).
I've tried to debug my code by using My project properties->Debug->Start Action->Start external program (with setting proper Working directory of course).
我的另一尝试是调试-> 附加以处理
My enother attempt was Debug->Attach to process
更新:我的模块和外部程序都使用一种资源.因此,外部程序将其释放,然后调用Process.Start(),等待我的进程退出并再次捕获资源.因此,当您的程序已经运行时,我无法附加.
UPDATE: Both my module and external program use one resource. So external program releases it, then calls Process.Start(), waits for my process to exit ans then capture the resource again. So I can't attach when your program is already running.
它们两者均失败-从未命中 Program.cs 中的断点.
Both of them failed - breakpoint in Program.cs was never hit.
那么,在这种情况下如何调试代码?
So, how can I debug my code in such circumstances?
推荐答案
我知道有两种方法可以轻松解决此问题.第一种方法是让程序请求调试器附加到它,这是它在Main中通过
There are two ways I know of to easily solve this problem. The first way is have your program request a debugger attach to it as the first thing it does in Main via Debugger.Launch()
public static void Main(string[] args)
{
Debugger.Launch();
//Rest of your code here
}
这将显示如下所示的对话框
This will make a dialog like the following show up
这将使您可以附加到正在运行的Visual Studio或启动新实例.
This will allow you to attach to your running visual studio or start a new instance.
当您无法使用以前的方法(例如,我认为它在服务内部不起作用)时解决此问题的另一种方法是在代码的开头放置一个循环,该循环将永远循环直到连接了调试器,这使您有足够的时间执行您之前尝试的附加到进程"方法,而不会让程序继续运行.
The other way to solve this when you can't use the previous method (for example I don't think it works inside services) is put a loop at the start of your code that will loop forever until a debugger is attached, this gives you enough time to do the "Attach to process" method you tried earlier without letting the program progress.
public static void Main(string[] args)
{
while(!Debugger.IsAttached)
{
Thread.Sleep(1000); //Sleep 1 second and then check again.
}
//Rest of your code here
}
这篇关于使用Process.Start()由外部程序启动我的代码时进行调试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!