简体   繁体   中英

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. 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. If you have a reference to the Dispatcher you can use that to pass the exception back to the UI thread. There are easier ways if you are using TPL, but to do it manually you would do:

_dispatcher = Dispatcher.CurrentDispatcher;

Before starting the background thread save a reference to the Dispatcher somewhere that the background thread will be able to access.

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

You can find plenty of other examples out there searching for Dispatcher

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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