为什么例外不会被WPF Dispatcher.Invoke传播? [英] Why exceptions are not propagated by WPF Dispatcher.Invoke?

查看:168
本文介绍了为什么例外不会被WPF Dispatcher.Invoke传播?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的假设例子。我有一个非常简单的WPF窗口与一个按钮。 Button.Click事件有一个这样的处理程序。

  Action doit =()=> 
{
Action error =()=> {throw new InvalidOperationException(test); };

try {
this.Dispatcher.Invoke(error,DispatcherPriority.Normal);
} catch(Exception ex){
System.Diagnostics.Trace.WriteLine(ex);
throw;
}
};
doit.BeginInvoke(null,null);

我预计这个例外会被 Trace .WriteLine 调用。相反,没有异常被捕获,应用程序中断。



有没有人知道可能的解释是为了发生这种情况?为了捕获由 Dispatcher.Invoke 调用的委托引发的异常,您建议使用什么解决方法?



更新1 :我在异常处理代码中放了一个 throw 。我不想实际忽略异常。我的问题的全部要点是正确处理。问题是异常处理代码永远不会执行。



请记住,这是一个假设的例子。我的真实代码看起来不像这样。另外,假设我无法更改要调用的方法中的代码。



更新2 :考虑这个类似的例子。而不是一个WPF窗口,我有一个Windows窗体窗口。它有一个与几乎完全相同的处理程序的按钮。唯一的区别是在调用代码中。这就像这样。

  this.Invoke(error); 

在Windows窗体中,执行异常处理代码。为什么不同?

解决方案

更新:要观察另一个线程中的异常,使用任务,将其排队到 Dispatcher 线程(使用 TaskScheduler.FromCurrentSynchronizationContext )和等待它,因此:

  var ui = TaskScheduler.FromCurrentSynchronizationContext(); 
动作doit =()=>
{
var error = Task.Factory.StartNew(
()=> {throw new InvalidOperationException(test);},
CancellationToken.None,
TaskCreationOptions.None,
ui);

try {
error.Wait();
} catch(Exception ex){
System.Diagnostics.Trace.WriteLine(ex);
}
};
doit.BeginInvoke(null,null);

UPDATED(再次):由于您的目标是可重用的组件,建议移动到任务的界面或基于 SynchronizationContext 的其他内容,例如基于事件的异步模式,而不是将组件基于 Dispatcher ISynchronizeInvoke



调度员基于组件仅适用于WPF / Silverlight; ISynchronizeInvoke 组件仅适用于Windows窗体。 基于SynchronizationContext 的组件可以透明地与WPF或Windows Forms一起工作,并且(更多的工作)ASP.NET,控制台应用程序,Windows服务等。



基于事件的异步模式是旧的推荐方式写入 SynchronizationContext 的组件;它仍然在.NET 3.5代码。但是,如果您使用的是.NET 4,任务并行库更加灵活,干净,功能强大。 TaskScheduler.FromCurrentSynchronizationContext 使用下面的 SynchronizationContext ,而且是编写需要此类同步的可重用组件的新方法。


Here's my hypothetical example. I have a very simple WPF window with a one Button. The Button.Click event has a handler that goes like this.

Action doit = () =>
{
    Action error = () => { throw new InvalidOperationException("test"); };

    try {
        this.Dispatcher.Invoke(error, DispatcherPriority.Normal);
    } catch (Exception ex) {
        System.Diagnostics.Trace.WriteLine(ex);
        throw;
    }
};
doit.BeginInvoke(null, null);

I would expect that the exception would be caught and written down by the Trace.WriteLine call. Instead, no exception is caught and the application breaks.

Does anybody knows of an possible explanation for this to happen? And what workaround do you suggest in order to catch exceptions thrown by the delegate invoked by Dispatcher.Invoke?

Update 1: I put a throw in the exception handling code. I don't want to actually ignore the exception. The whole point of my question is to handle it correctly. The problem is that the exception handling code is never executed.

Remember that this is an hypothetical example. My real code does not look like that. Also, assume that I can't change the code in the method to be invoked.

Update 2: Consider this similar example. Instead of a WPF window, I have a Windows Forms window. It has a button with the almost exactly the same handler. The only difference is in the invocation code. It goes like this.

this.Invoke(error);

In Windows Forms, the exception handling code is executed. Why the difference?

解决方案

UPDATED: To observe the exception in the other thread, you want to use a Task, queue it to the Dispatcher thread (using TaskScheduler.FromCurrentSynchronizationContext), and wait on it, as such:

var ui = TaskScheduler.FromCurrentSynchronizationContext();
Action doit = () => 
{ 
    var error = Task.Factory.StartNew(
        () => { throw new InvalidOperationException("test"); },
        CancellationToken.None,
        TaskCreationOptions.None,
        ui); 

    try { 
        error.Wait(); 
    } catch (Exception ex) { 
        System.Diagnostics.Trace.WriteLine(ex); 
    } 
}; 
doit.BeginInvoke(null, null); 

UPDATED (again): Since your goal is a reusable component, I do recommend moving to a Task-based interface or something else based on SynchronizationContext such as the event-based asynchronous pattern, instead of basing the component on Dispatcher or ISynchronizeInvoke.

Dispatcher-based components only work on WPF/Silverlight; ISynchronizeInvoke-based components only work on Windows Forms. SynchronizationContext-based components will work with WPF or Windows Forms transparently, and (with a bit more work) ASP.NET, console apps, windows services, etc.

The event-based asynchronous pattern is the old recommended way of writing SynchronizationContext-based components; it's still around for .NET 3.5-era code. If you're on .NET 4, though, the task parallel library is much more flexible, clean, and powerful. The TaskScheduler.FromCurrentSynchronizationContext uses SynchronizationContext underneath, and is the New Way to write reusable components that need this kind of synchronization.

这篇关于为什么例外不会被WPF Dispatcher.Invoke传播?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆