简体   繁体   中英

Wpf handling exception throwing by task

How can i handle an exception on wpf, that was throwed within worker thread?

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
    {
        var task = Task.Factory.StartNew(() =>
        {
            Debug.WriteLine("Hello");
            throw new Exception();
        });

        try
        {
            task.Wait();
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.Message);
        }

    }
}  

Or it is not common to handle an exception in this way?

task.ContinueWith(task => {
      if (task .Exception != null)
                    {
                        //.........
                    }

},TaskContinuationOptions.OnlyOnFaulted);

Take a look here http://www.codeproject.com/Articles/152765/Task-Parallel-Library-of-n#handlingExceptions

You can catch the [System.AggregateException] to examine if you can handle any of its InnerExceptions . See the example below.

var task = Task.Factory.StartNew(() =>
{
    Debug.WriteLine("Hello");
    throw new InvalidOperationException(); // throw an InvalidOperationException that is handled.
});

try
{
    task.Wait();
}
catch (AggregateException ae)
{
    ae.Handle((x) =>
    {
        if (x is InvalidOperationException) // We know how to handle this exception.
        {
            Console.WriteLine("InvalidOperationException error.");
            return true; // Continue with operation.
        }
        return false; // Let anything else stop the application.
    });
}

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