关闭

.net framework 4.0 TaskFactory类的使用

808人阅读 评论(0) 收藏 举报
分类:

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();
        }
    }
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:1149171次
    • 积分:14825
    • 等级:
    • 排名:第770名
    • 原创:465篇
    • 转载:111篇
    • 译文:2篇
    • 评论:121条
    最新评论