简体   繁体   English

WPF将异常消息从ThreadPool线程传递到UI

[英]WPF pass exception message from ThreadPool thread to UI

Whenever an exception occurs in a threadpool thread. 每当线程池线程中发生异常时。 I thought I'd raise an event that the UI thread would respond to. 我以为会引发UI线程会响应的事件。 But I need to pass the exception message. 但是我需要传递异常消息。 Can someone give me some idea to do this? 有人可以给我一些想法吗?

如果您已在线程中处理了异常,则可以在catch块中使用错误消息,并将其发送到UI线程的分派器。

You can just watch for unhandled exceptions in the app domain with the events: 您可以通过事件在应用程序域中监视未处理的异常:

Application.Current.DispatcherUnhandledException += Current_DispatcherUnhandledException;
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

But it would probably be better to wrap the thread in a try catch and manually marshal the exception back to the UI thread. 但是,最好将线程包装在try catch中,然后手动将异常封送回UI线程。 If you have a reference to the Dispatcher you can use that to pass the exception back to the UI thread. 如果您有对Dispatcher的引用,则可以使用该引用将异常传递回UI线程。 There are easier ways if you are using TPL, but to do it manually you would do: 如果您使用的是TPL,则有更简单的方法,但是要手动进行,您可以执行以下操作:

_dispatcher = Dispatcher.CurrentDispatcher;

Before starting the background thread save a reference to the Dispatcher somewhere that the background thread will be able to access. 在启动后台线程之前,请将对Dispatcher的引用保存在后台线程将能够访问的某个位置。

private void FailedWorking(Exception ex)
{
    _dispatcher.BeginInvoke(DispatcherPriority.Normal, (NotifyWorkerFailed)_notifyFailedMethod, ex);
}

Then when you want to raise the exception on the UI thread use Dispatcher.BeginInvoke and either pass it a delegate method that will handle the exception or you could just create an Action that throws 然后,当您想在UI线程上引发异常时,请使用Dispatcher.BeginInvoke并向其传递将处理异常的委托方法,或者您可以仅创建引发异常的Action。

You can find plenty of other examples out there searching for Dispatcher 您可以找到许多其他示例来查找Dispatcher

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM