首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >是否有可能在c# 4.0的c# WPF应用程序中全局捕获意外错误

是否有可能在c# 4.0的c# WPF应用程序中全局捕获意外错误
EN

Stack Overflow用户
提问于 2011-10-22 20:44:31
回答 2查看 1.1K关注 0票数 1

是否有可能在c# WPF应用程序- c# 4.0中全局捕获意外错误

我发现DispatcherUnhandledException能够捕获UI线程错误,但实际上我需要TPL线程。UnhandledException能够捕获线程错误,但它仍然会导致软件终止。

因此,任何解决方案都可以捕获线程中未处理的异常,而不是UI线程中的异常,并且仍然让软件运行而不是终止。线程是TPL线程。(任务并行库)

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-10-22 20:52:37

将处理DispatcherUnhandledException的一部分添加到您的配置文件中

代码语言:javascript
复制
<configuration>
  <runtime>  
    <legacyUnhandledExceptionPolicy enabled="1"/>
  </runtime>
</configuration>

这可以防止辅助线程异常关闭应用程序。

票数 2
EN

Stack Overflow用户

发布于 2011-10-23 02:40:06

您可以在第三方物流中使用Custom Escalation Policy来寻址您的case.You,方法是向静态System.Threading.Tasks.TaskScheduler.UnobservedTaskException成员添加一个事件处理程序

代码语言:javascript
复制
    class Test
    {
        static void Main(string[] args)
        {
            // create the new escalation policy
            TaskScheduler.UnobservedTaskException += (object sender, UnobservedTaskExceptionEventArgs eventArgs) =>
             {
                // mark the exception as being handled
                eventArgs.SetObserved();
                // get the aggregate exception and process the contents
                 ((AggregateException)eventArgs.Exception).Handle(ex =>
                    {
                        // write the type of the exception to the console
                         Console.WriteLine("Exception type: {0}", ex.GetType());
                        return true;
                    });
              };
            // create tasks that will throw an exception
            Task task1 = new Task(() =>
            {
                throw new NullReferenceException();
            });
            Task task2 = new Task(() =>
            {
                throw new ArgumentOutOfRangeException();
            });
            // start the tasks
            task1.Start(); task2.Start();
            // wait for the tasks to complete - but do so
            // without calling any of the trigger members
            // so that the exceptions remain unhandled
            while (!task1.IsCompleted || !task2.IsCompleted)
            {
                Thread.Sleep(500);
            }
            // wait for input before exiting
            Console.WriteLine("Press enter to finish and finalize tasks");
            Console.ReadLine();
        }
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7859613

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档