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
248 views
in Technique[技术] by (71.8m points)

c# - How to prevent Debug.Assert(...) to show a modal dialog

I have a couple of libraries which use Debug.Assert(...). I think that the Debug.Assert(...) are fine and I still want them to execute, but I don't want them to block the execution of my application. Ideally, I would only like them to be logged somewhere.

Given that I can't change the code of the libraries (and that I still want to compile in debug and run the assertion), how do I prevent Debug.Assert(...) to show a modal dialog?

In addition, I would like to make sure that the main program continues when an Assert occurs (same behavior as the Ignore button).

Thanks!

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

I wouldn't recommend it. The problem is that Debug.Assert is only supposed to be fired when you have bugs in your code. If you just ignore them or don't fix them, then you are doing your users a disservice. If, on the other hand, you're firing Debug.Assert for things that aren't bugs, then you're also doing your users a disservice (by reducing the impact of Debug.Assert).

Having said that, you can disable it. The first thing you need to do is remove the default listener from the Debug.Listeners collection:

Debug.Listeners.Clear();

Then, add your own instead:

Debug.Listeners.Add(new MyTraceListener());

You need to create a class that inherits from TraceListener:

class MyTraceListener : TraceListener
{
    // ...

    public override void Fail(string msg, string detailedMsg)
    {
        // log the message (don't display a MessageBox)
    }
}

The important method is the TraceListener.Fail method, which in the implementation of DefaultTraceListener is what displays the message box.


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

...