Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

debugging - How to wait until remote .NET debugger attached

Today I ran into a problem were I needed to remote-debug a program. The program was launched from another system, so I really don't have an opportunity to interact with it on the command line. I could change its source easily though.

What I needed to happen was for the program to start normally, and then wait for me to attach to it with a debugger. I couldn't come up with a way to do it that made me happy. I did find the bug, but without the help of the debugger.

while(true) { }

Kept the process alive, and then I could "set next statement" with the debugger, but it seemed awkward and rude.

Console.ReadLine();

Seemed odd to type since there wasn't actually a Console for me to press enter at. (It didn't work, either. Set next statement and then run takes you back into the ReadLine() wait.)

So what kind of code can I insert into a .NET/CLR/C# program that says "wait here until I can attach with a debugger"?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use the System.Diagnostics.Debugger.IsAttached property to check if a debugger is attached to the process. This application will wait until a debugger has been attached:

using System;
using System.Diagnostics;
using System.Threading;

namespace DebugApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Waiting for debugger to attach");
            while (!Debugger.IsAttached)
            {
                Thread.Sleep(100);
            }
            Console.WriteLine("Debugger attached");
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...