【问题标题】:Should exceptions thrown in UI thread but originating in another thread raise UI ThreadException?在 UI 线程中引发但源自另一个线程的异常是否应该引发 UI ThreadException?
【发布时间】:2015-01-27 22:56:25
【问题描述】:

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

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

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

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

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

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

【问题讨论】:

    标签: .net multithreading exception-handling


    【解决方案1】:

    问题在于 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 将对委托中的执行代码“一劳永逸”。这也意味着您不能像我们使用 Send 方法那样捕获异常。假设抛出异常,将是 UI 线程将得到它;取消处理异常将终止 UI 线程。

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-08
    • 2017-04-24
    • 1970-01-01
    • 2022-07-31
    相关资源
    最近更新 更多