0

我有 WPF 应用程序,我想在按钮单击处理程序中启动多个任务(每个任务都可以执行长时间运行的操作)。

我想向用户报告所有任务是否成功,或者如果没有,个别任务的错误是什么。

尽管区分至少一个异常或全部成功,但我看不到一种很好的方法。

using System;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Windows;

namespace WPFTaskApp
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {

            Task t1 = new Task(DoSomething);
            Task t2 = new Task(DoSomethingElse);

            t1.Start();
            t2.Start();

            // So now both tasks are running.
            // I want to display one of two messages to the user:
            // If both tasks completed ok, as in without exceptions, then notify the user of the success
            // If an exception occured in either task notify the user of the exception.

            // The closest I have got to the above is to use ContinueWhenAll, but this doesn't let
            // me filter on the completion type

            Task[] tasks = { t1, t2 };

            Task.Factory.ContinueWhenAll(tasks, f =>
                {
                    // This is called when both tasks are complete, but is called
                    // regardless of whether exceptions occured.
                    MessageBox.Show("All tasks completed");
                });
        }

        private void DoSomething()
        {
            System.Threading.Thread.Sleep(1000);
            Debug.WriteLine("DoSomething complete.");
        }

        private void DoSomethingElse()
        {
            System.Threading.Thread.Sleep(4000);
            throw new Exception();
        }
    }
}

非常感谢您的帮助。

4

1 回答 1

5

在您的后续工作中,您可以检查每个任务是否有异常:

Task.Factory.ContinueWhenAll(tasks, f =>
            {
                if (t1.Exception != null)
                {
                     // t1 had an exception
                }
                if (t2.Exception != null)
                {
                     // t2 had an exception
                }

                // This is called when both tasks are complete, but is called
                // regardless of whether exceptions occured.
                MessageBox.Show("All tasks completed");
            });
于 2013-06-12T19:32:09.527 回答