程序Ⅰ:通过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 t 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. 基于IDL 的WebRS系统设计图

    图1 用例图 图2 结构图

  2. 正确使用String,StringBuffer,StringBuilder

    很多时候在实际中,我们很常用的就是字符串String. 对于它,网上已经说的很多了. 我就说一点是特别重要的需要记住的,String赋值之后它就是不能被改变的. 也就是这一点,导致了String在操作 ...

  3. 提升html5的性能体验系列之五webview启动速度优化及事件顺序解析]

    webview加载时有3个事件.触发顺序为loading.titleUpdate.loaded.webview开始载入页面时触发loading,载入过程中如果title已经解析并赋予新值,则触发tit ...

  4. 在程序中用new ClassPathXmlApplicationContext()的注意事项

    http://blog.csdn.net/budapest/article/details/38493003

  5. postfix疯狂外发垃圾邮件

    分析 一.查找main.cf配置文件 localhost# find / -name main.cf /etc/postfix/main.cf 二.打开/etc/postfix/main.cf来看看. ...

  6. 转:移植SlidingMenu Android library,和安装example出现的问题解决

    很多项目都用到类似左侧滑动菜单的效果,比如facebook,evernote,VLC for android等等,这很酷 源代码可以从GitHub的https://github.com/jfeinst ...

  7. JAVA和C++区别

    1.指针 JAVA语言让编程者无法找到指针来直接访问内存无指针,并且增添了自动的内存管理功能,从而有效地防止了c/c++语言中指针操作失误,如野指针所造成的系统崩溃.但也不是说JAVA没有指针,虚拟机 ...

  8. PhpStorm11.0 配置在浏览器中打开文件

    转自:http://www.bubuko.com/infodetail-1420190.html 点击File-Settings-Deployment . 点+按钮增加服务器 Mapping 设置工程 ...

  9. Allegro PCB -如何做自定义焊盘

    1.如何创建自定义焊盘,比如这种形状的焊盘. (1).打开PCB Editor –>Allegro PCB Design ->New,在类型中选择Shape symbol,并输入名字,比如 ...

  10. Jedis使用示例

    http://javacrazyer.iteye.com/blog/1840161 http://www.cnblogs.com/edisonfeng/p/3571870.html