抽象线程之Parallel类

该类定义了并行的For和Foreach方法,Parallel类使用多个任务,因此需要多个线程来完成这个作业

代码及简单注释如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
        //Parallel.For多次调用同一个方法
        static public void formathod()
        {
            //函数原型:Parallel.For<TLocal>(Int32, Int32, Func<TLocal>, Func<Int32, ParallelLoopState, TLocal, TLocal>, Action<TLocal>)
            //定义一个本地数据为string类型的数据,执行Func<TLocal>委托对本地数据初始化,然后将每个迭代调用一次Func<Int32, ParallelLoopState, TLocal, TLocal>委托,最后执行 Action<TLocal>委托对本地状态进行最后处理
            Parallel.For<string>(0, 20, () =>
                {
                    Console.WriteLine("Task{0} is begin", Task.CurrentId);
                    return string.Format("Task{0}", Thread.CurrentThread.ManagedThreadId);
                },
                (i, pls, str) =>
                {
                    Thread.Sleep(1000);
                    return string.Format("Task{0}", i);
                },
                (str) =>
                {
                    Console.WriteLine("{0} is over", str);
                });
        }
        static public void formathod1()
        {
            //函数原型:For(Int32, Int32, Action<Int32>)
            //以下实例则为从0迭代到10,每一次都调用Action<i>这个委托,返回参数提供了循环是否结束的消息
            ParallelLoopResult result =
            Parallel.For(0, 10, i =>
                {
                    Thread.Sleep(100);
                    Console.WriteLine("Thread{0},Task{1}", Thread.CurrentThread.ManagedThreadId, Task.CurrentId);
                });
            Console.WriteLine(result.IsCompleted);
        }
        static public void foreachmethod()
        {
            //Parallel.ForEach函数原型为:Parallel.ForEach<TSource>(IEnumerable<TSource>, Action<TSource>)
            //IEnumerable<TSource>为公开枚举数,该枚举数支持在指定类型的集合上进行简单迭代。
            //以下代码为迭代集合上的元素,并为他们执行lambda表达式(Action<TSource>委托)
            string[] data = { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten" };
            Parallel.ForEach<string>(data, s =>
                {
                    Thread.Sleep(1000);
                    Console.WriteLine(s);
                });
        }
        static void Main(string[] args)
        {

            formathod1();
            formathod();
            foreachmethod();
        }
    }
}
posted @ 2014-07-16 11:17  runninglzw  阅读(216)  评论(0编辑  收藏  举报