首页 > 代码库 > C# TPL学习(4个程序)

C# TPL学习(4个程序)

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

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启动任务并接收任务的返回值

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

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类统计程序段的运行时间

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

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学习(4个程序)