从按钮单击(UI线程)运行多个任务 - 如何知道它们是否全部成功或某些失败?

P2l*_*P2l 0 c# multithreading task task-parallel-library

我有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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

非常感谢您的帮助.

Ree*_*sey 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");
            });
Run Code Online (Sandbox Code Playgroud)