How to force an application crash when AccessViolationException is detected

旧时模样 提交于 2019-12-06 07:31:48
Chris O'Neill

Try this:

this.Dispatcher.BeginInvoke((Action) delegate 
{
    User32.SendMessage(...);
}, DispatcherPriority.Input);

The application should crash the way you want it to.


Most of the examples I've seen that call Dispatcher.BeginInvoke() with an anonymous delegate use an Action.


Why does this happen?

It seems that the CLR code, way down in:

at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.DispatcherOperation.InvokeImpl()

invokes an Action directly, most other delegates are invoked using reflection.

The reflection mechanism will wrap exceptions in a TargetInvocationException.

See this answer to another question to explain.


Other special case delegates which will not wrap exceptions are: DispatcherOperationCallback and SendOrPostCallback, though to work they have to be called with a single argument.

this.Dispatcher.BeginInvoke(DispatcherPriority.Input,
    (SendOrPostCallback)(delegate(object o)
    {
        throw new AccessViolationException(o.ToString());
    }), "test");

Use below code to close the application after getting the exception.

Environment.Exit(1);    

Exit needs a parameter called exitcode. If exitcode=0 means there was no error. Supply a non-zero exit code to to reflect an error.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!