程序Ⅰ:通过Task类创建新线程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
 
namespace Test000
{
    class Program
    {
        /// <summary>
        /// Task类封装
        /// </summary>
        class MyTask
        {
            /// <summary>
            /// 第一个Task类,每秒计数,计数5次
            /// </summary>
            public static void T1()
            {
                Console.WriteLine("Task #{0}: Begin!", Task.CurrentId);
                for (int i = 0; i < 5; i++)
                {
                    Thread.Sleep(1000);
                    Console.WriteLine("Task #{0}: {1}", Task.CurrentId, i);
                }
                Console.WriteLine("Task #{0}: Terminated!", Task.CurrentId);
            }
 
            /// <summary>
            /// 第二个Task类,每秒计数,计数5次
            /// </summary>
            public static void T2()
            {
                Console.WriteLine("Task #{0}: Begin!", Task.CurrentId);
                Thread.Sleep(500);
                for (int i = 0; i < 5; i++)
                {
                    Thread.Sleep(1000);
                    Console.WriteLine("Task #{0}: {1}", Task.CurrentId, i);
                }
                Console.WriteLine("Task #{0}: Terminated!", Task.CurrentId);
            }
        }
 
        static void Main(string[] args)
        {
            //建立两个Task
            Task tsk1 = new Task(MyTask.T1);
            Console.WriteLine("Task #{0}: Constructed!", tsk1.Id);
            Task tsk2 = new Task(MyTask.T2);
            Console.WriteLine("Task #{0}: Constructed!", tsk1.Id);
 
            //运行Task
            tsk1.Start();
            tsk2.Start();
 
            //等待Task运行结束
            WaitAll(tsk1, tsk2);
 
            Console.ReadLine();
        }
 
        /// <summary>
        /// 等待所有的Task运行结束
        /// </summary>
        /// <param name="tsks">等待的Task类</param>
        public static void WaitAll(params Task[] tsks)
        {
            foreach (var in tsks)
            {
                t.Wait();
            }
        }
    }
}

运行结果

程序Ⅱ:通过TaskFactory启动任务并接收任务的返回值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Test001
{
    class Program
    {
        /// <summary>
        /// Task类封装
        /// </summary>
        class MyTask
        {
            /// <summary>
            /// 求1+2+...+n的和
            /// </summary>
            /// <param name="n">数n</param>
            /// <returns></returns>
            public static int Sum(object n)
            {
                int x = (int)n;
                int sum = 0;
                for (int i = 1; i <= x; i++)
                {
                    sum += i;
                }
                return sum;
            }
        }
 
        static void Main(string[] args)
        {
            Task<int> tsk = Task<int>.Factory.StartNew(MyTask.Sum, 100);
            Console.WriteLine("Result is: " + tsk.Result);
 
            Console.ReadLine();
        }
    }
}

运行结果

程序Ⅲ:通过Parallel类的Invoke函数,并行调用多个Task

本程序中通过Lambda表达式来建立新的Task

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
 
namespace Test002
{
    class Program
    {
        static void Main(string[] args)
        {
            Parallel.Invoke
                (
                    () =>
                    {
                        Console.WriteLine("Task #{0}: Begin!", Task.CurrentId);
                        for (int i = 0; i < 5; i++)
                        {
                            Thread.Sleep(1000);
                            Console.WriteLine("Task #{0}: {1}", Task.CurrentId, i);
                        }
                        Console.WriteLine("Task #{0}: Terminated!", Task.CurrentId);
                    },
                    () =>
                    {
                        Console.WriteLine("Task #{0}: Begin!", Task.CurrentId);
                        Thread.Sleep(500);
                        for (int i = 0; i < 5; i++)
                        {
                            Thread.Sleep(1000);
                            Console.WriteLine("Task #{0}: {1}", Task.CurrentId, i);
                        }
                        Console.WriteLine("Task #{0}: Terminated!", Task.CurrentId);
                    }
                );
 
            Console.ReadLine();
        }
    }
}

运行结果

程序Ⅳ:通过Parallel类的For和FoeEach函数,并行调用多个Task

本程序中,通过Stopwatch类统计程序段的运行时间

从例中可以看出:不是所有的循环在并行化时都是有效的。通常,对于小型循环或执行非常简单的操作的循环来说,使用顺序循环比并行循环更加快速

 
 
 
 
 
 
 
 
 
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Test003
{
    class Program
    {
        /// <summary>
        /// 示例函数
        /// </summary>
        /// <param name="n">参数</param>
        public static void DoSomeThing(int n)
        {
            int sum = 0;
            for (int i = 0; i < n * 100; i++)
            {
                sum += i;
            }
        }
 
        static void Main(string[] args)
        {
            //计时工具,需要System.Diagnostics
            Stopwatch sw = new Stopwatch();
 
            //统计依次顺序调用函数的时间
            sw.Start();
            for (int i = 100; i < 105; i++)
            {
                DoSomeThing(100);
            }
            sw.Stop();
            Console.WriteLine("TotalTime: {0}", sw.Elapsed.TotalMilliseconds);
            sw.Reset();
 
            Console.WriteLine("===========");
 
            //统计并行调用函数的时间
            sw.Start();
            Parallel.For(100, 105, DoSomeThing);
            sw.Stop();
            Console.WriteLine("TotalTime: {0}", sw.Elapsed.TotalMilliseconds);
            sw.Reset();
 
            Console.WriteLine("===========");
 
            //统计并行调用函数的时间
            sw.Start();
            Parallel.ForEach(new int[5] { 100, 101, 102, 103, 104 }, DoSomeThing);
            sw.Stop();
            Console.WriteLine("TotalTime: {0}", sw.Elapsed.TotalMilliseconds);
 
            sw.Reset();
            Console.ReadLine();
        }
    }
}

运行结果

END

C# TPL学习的更多相关文章

  1. c#中@标志的作用 C#通过序列化实现深表复制 细说并发编程-TPL 大数据量下DataTable To List效率对比 【转载】C#工具类:实现文件操作File的工具类 异步多线程 Async .net 多线程 Thread ThreadPool Task .Net 反射学习

    c#中@标志的作用   参考微软官方文档-特殊字符@,地址 https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/toke ...

  2. PHP-自定义模板-学习笔记

    1.  开始 这几天,看了李炎恢老师的<PHP第二季度视频>中的“章节7:创建TPL自定义模板”,做一个学习笔记,通过绘制架构图.UML类图和思维导图,来对加深理解. 2.  整体架构图 ...

  3. AngularJs学习笔记(制作留言板)

    原文地址:http://www.jmingzi.cn/?post=13 初学Anjularjs两天了,一边学一边写的留言板,只有一级回复嵌套.演示地址 这里总结一下学习的过程和笔记.另外,看看这篇文章 ...

  4. gulp + webpack + sass 学习

    笔记: new webpack.optimize.CommonsChunkPlugin 核心作用是抽离公共代码,chunks:['index.js','main.js'] 另一个作用就是单独生成一个j ...

  5. 学习 React(jsx语法) + es2015 + babel + webpack

    视频学习地址: http://www.jtthink.com/course/play/575 官方地址 https://facebook.github.io/react/ 神坑: 1.每次this.s ...

  6. Python学习记录day5

    title: Python学习记录day5 tags: python author: Chinge Yang date: 2016-11-26 --- 1.多层装饰器 多层装饰器的原理是,装饰器装饰函 ...

  7. MVC架构学习之Smarty学习——病来而蔫

    前两天是五一小长假,而每次假期都想着如何如何刻苦一番,往往是自作多情.. 当然这次是有小病在身,多个借口吧. 一有病就蔫的不行...要锻炼了啊,脚估计也差不多了,游泳试试吧这周. 这次学习Smarty ...

  8. Java学习资料

    微信扫码:http://v.dxsbb.com/jisuanji/Java之家:http://www.javazhijia.com/bs/biye/137.html一些 http://www.ibei ...

  9. Thinkphp学习回顾(一)之基本结构目录

    TP框架的学习一般都是从了解框架的基本结构开始的,每个文件都有其专属的作用,我的TP框架的回顾也从基本结构开始讲起. 一.ThinkPHP的获取 http://www.thinkphp.cn   这是 ...

随机推荐

  1. POJ 2289 Jamie's Contact Groups

    二分答案+网络最大流 #include<cstdio> #include<cstring> #include<cmath> #include<vector&g ...

  2. 博弈论最简单例子TacTicToe

    博弈论是人工智能中的一个分支.顾名思义就是下棋的算法.当然引申出来的应用可能不止用来下棋,也可以用来做游戏或者模拟战争策略等. 博弈的基本算法也是模拟人的思维,比如当自己下子时遍历所有可能寻求最有利步 ...

  3. 配置Eclipse支持java和xml文件的代码补全功能

    百度经验:jingyan.baidu.com 本文介绍如何配置Eclipse,使得在编写代码时无论是*.java还是*.xml文件都能够通过使用ALT+/快捷键实现代码不全的功能. 本文实验环境为:W ...

  4. HDU 1527 取石子游戏(威佐夫博弈)

    基础威佐夫博弈,判断奇异局势即可,判断方式为k为两数之差绝对值,(sqrt(5) + 1) / 2 * k若等于两数小者则为奇异局势,也就是必败态. #include<stdio.h> # ...

  5. Kubernetes 1.4 部署

    k8s 1.4 新版本部署 测试环境: node-: 10.6.0.140 node-: 10.6.0.187 node-: 10.6.0.188 kubernetes 集群,包含 master 节点 ...

  6. EM算法--第一篇

    在统计计算中,最大期望(EM)算法是在概率(probabilistic)模型中寻找参数最大似然估计或者最大后验估计的算法,其中概率模型依赖于无法观测的隐藏变量(LatentVariable).最大期望 ...

  7. FreeRTOS初步认识

    源:FreeRTOS初步认识 用了半天时间对FreeRTOS有了一个初步的认识,大概总结一下,其中混杂了系统实现和实际应用方面的问题. 现只是以应用为目的,实现方面待以后进一步研究. 1.FreeRT ...

  8. 控制流(swift)

    检测API是否可用 if #available(iOS 9, OSX 10.10, *) { // 在 iOS 使用 iOS 9 APIs , 并且在 OS X 使用 OS X v10.10 APIs ...

  9. (中等) HDU 5293 Tree chain problem,树链剖分+树形DP。

    Problem Description   Coco has a tree, whose vertices are conveniently labeled by 1,2,…,n.There are ...

  10. (中等) HDU 1495 非常可乐,BFS。

    Description 大家一定觉的运动以后喝可乐是一件很惬意的事情,但是seeyou却不这么认为.因为每次当seeyou买了可乐以后,阿牛就要求和seeyou一起分享 这一瓶可乐,而且一定要喝的和s ...