程序Ⅰ:通过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. 修改TabPageIndicator下划线的颜色

    <style name="CustomTabPageIndicator" parent="Widget.TabPageIndicator"> < ...

  2. mkconfig文件解析

    #!/bin/sh -e #mkconfig 100ask24x0 arm arm920t 100ask24x0 Null s3c24x0#s0                     s1      ...

  3. mac版MyEclipse的安装及创建web项目

    这两天快被MyEclipse整死了,因为电脑是mac系统的,安装MyEclipse mac破解版时一直是不成功,弄了一天多才行,接着创建web项目HttpServlet在Tomcat发布时总是出现40 ...

  4. mysql 字符集配置

    查看和设置MySQL数据库字符集作者:scorpio 2008-01-21 10:05:17 标签: 杂谈 Liunx下修改MySQL字符集:1.查找MySQL的cnf文件的位置find / -ina ...

  5. nginx的RTMP协议服务器

    nginx的RTMP协议服务器 by ahuner 通过以下的配置,可以使nginx接收RTMP流,并在web上播放实时视频. 1.openssl安装 nginx需要http_ssl_module模块 ...

  6. D. Bear and Two Paths(贪心构造)

    D. Bear and Two Paths time limit per test 2 seconds memory limit per test 256 megabytes input standa ...

  7. mysql 索引对于select速度提升作用实验

    说明:News2在News的基础上把is_active加上索引. mysql> select count(*) from News2 where is_active=1; +---------- ...

  8. Struts2--DomainModel接收参数---使用广泛!!!

    1. JSP文件调用格式: <a href="user/user!add?user.name=a&user.age=8">添加用户</a> 2. s ...

  9. Android——apk反编译

    一.工具准备: 1.dex2jar:http://code.google.com/p/dex2jar/downloads/list 2.JD-GUI:windows:http://laichao.go ...

  10. PHP中的ORM

    周末找个时间好好写一写 ORM相关的东西,整理整理. 参考:http://www.cnblogs.com/52fhy/p/5353181.html http://www.cnblogs.com/52f ...