UI 线程中抛出但源自另一个线程的异常是否应该引发 UI ThreadException?

Should exceptions thrown in UI thread but originating in another thread raise UI ThreadException?

注意:这是概念框架问题,而不是 VB.Net 特定问题。也可以在 C# 中询问。

我在应用程序启动时添加了以下处理程序:

AddHandler System.Windows.Forms.Application.ThreadException, AddressOf UIThreadException

它工作得很好,处理程序得到每个异常

除非 我使用标准 System.Windows.Forms.WindowsFormsSynchronizationContext.Send() 将自定义后台线程(队列处理)的调用传递到主线程。然后在主线程中成功执行,但抛出的任何异常都不会触发上述处理程序,并抛出未处理的异常。

您有什么经验,这是框架的预期行为吗?

问题出在 Send(...) 方法上。

查看来源:

// Summary:
//     When overridden in a derived class, dispatches a synchronous message to a
//     synchronization context.
// Parameters:
//   d:
//     The System.Threading.SendOrPostCallback delegate to call.
//   state:
//     The object passed to the delegate.
public virtual void Send(SendOrPostCallback d, object state);

这个方法是同步工作的,所以它基本上是在线程内部处理的。 但是我们可以看看Post(...)方法。

// Summary:
//     When overridden in a derived class, dispatches an asynchronous message to
//     a synchronization context.
// Parameters:
//   d:
//     The System.Threading.SendOrPostCallback delegate to call.
//   state:
//     The object passed to the delegate.
public virtual void Post(SendOrPostCallback d, object state);

这意味着Post不会等待委托的执行完成。 Post 将 "Fire and Forget" 关于委托内的执行代码。这也意味着您不能像我们使用 Send 方法那样捕获异常。假设抛出一个异常,UI 线程会得到它;取消处理异常将终止 UI 线程。

此处的其他信息: http://www.codeproject.com/Articles/31971/Understanding-SynchronizationContext-Part-I