.net framework 4.0 TaskFactory类的使用

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WinFormApp
{
    public partial class Form3 : Form
    {
        public Form3()
        {
            InitializeComponent();


        }
        System.Threading.CancellationTokenSource cts = new System.Threading.CancellationTokenSource();

        void Run()
        {
            System.Threading.Tasks.TaskFactory taskFactory = new System.Threading.Tasks.TaskFactory();
            System.Threading.Tasks.Task[] tasks = new System.Threading.Tasks.Task[] {
                taskFactory.StartNew(()=>TaskDo(cts.Token),cts.Token),
                taskFactory.StartNew(()=>TaskDo(cts.Token),cts.Token),
                taskFactory.StartNew(()=>TaskDo(cts.Token),cts.Token),
                taskFactory.StartNew(()=>TaskDo(cts.Token),cts.Token)
            };

 


            taskFactory.ContinueWhenAll(tasks, TaskEnd, System.Threading.CancellationToken.None);

        }

        void TaskEnd(System.Threading.Tasks.Task[] tasks)
        {
            StringBuilder sb = new StringBuilder();

            foreach (System.Threading.Tasks.Task task in tasks)
            {
                sb = new StringBuilder();
                sb.AppendLine("任务已经完成...");
                sb.AppendLine("是否因为被取消而完成:" + task.IsCanceled.ToString());
                sb.AppendLine("成功完成:" + task.IsCompleted.ToString());
                sb.AppendLine("是否因为发生异常而完成:" + task.IsFaulted.ToString());

                ThreadInvoke.SetEventInvokeValue(richTextBox1, sb.ToString());
            }


        

        }

        string TaskDo(System.Threading.CancellationToken ct)
        {
            int i = 0;
            while (i < 10)
            {
                if (ct.IsCancellationRequested)
                {
                    break;
                }
                ThreadInvoke.SetEventInvokeValue(richTextBox1, "执行任务中......" + i.ToString());
                System.Threading.Thread.Sleep(100);
                i++;
            }
            return "谢谢您的等待...";

        }

        private void button1_Click(object sender, EventArgs e)
        {
            Run();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            cts.Cancel();
        }
    }
}

你可能感兴趣的:(.net framework 4.0 TaskFactory类的使用)