码迷,mamicode.com
首页 > 其他好文 > 详细

Parallel类(简化Task 操作)

时间:2016-04-16 15:24:11      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:

Parallel类

Parallel类是对线程的一个很好抽象。该类位于System.Threading.Tasks命名空间中,提供了数据和任务并行性。

1.用Parallel.For()方法循环

        //// simple scenario
        ParallelLoopResult result =
            Parallel.For(0, 10, async i =>
                {
                    Console.WriteLine("{0}, task: {1}, thread: {2}", i,
                       Task.CurrentId, Thread.CurrentThread.ManagedThreadId);

                    await Task.Delay(10);
                    Console.WriteLine("{0}, task: {1}, thread: {2}", i,
                      Task.CurrentId, Thread.CurrentThread.ManagedThreadId);
                });
        Console.WriteLine("is completed: {0}", result.IsCompleted);

技术分享

2.提前停止Parallel.For

For()方法的一个重载版本接受第三个Action<int, ParallelLoopState>类型的参数。使用这些参数定义一个方法,就可以调用ParallelLoopState的Break()或Stop()方法,以影响循环结果。

      // breaking early
        ParallelLoopResult result =
            Parallel.For(10, 40, (int i, ParallelLoopState pls) =>
                {
                    Console.WriteLine("i: {0} task {1}", i, Task.CurrentId);
                    Thread.Sleep(10);
                    if (i > 15)
                        pls.Break();
                });
        Console.WriteLine("Is completed: {0}", result.IsCompleted);
        if (!result.IsCompleted)
            Console.WriteLine("lowest break iteration: {0}", result.LowestBreakIteration);

技术分享

3.使用Parallel.ForEach()方法循环

      string[] data = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve" };

      ParallelLoopResult result =
          Parallel.ForEach<string>(data, s =>
              {
                Console.WriteLine(s);
              });


      Parallel.ForEach<string>(data,
          (s, pls, l) =>
          {
            Console.WriteLine("{0} {1}", s, l);

          });

技术分享

4.通过Parallel.Invoke()方法调用多个方法

    static void ParallelInvoke()
    {
      Parallel.Invoke(Foo, Bar);
    }

    static void Foo()
    {
      Console.WriteLine("foo");
    }

    static void Bar()
    {
      Console.WriteLine("bar");
    }

技术分享

 

 

推荐阅读:改善C#程序的建议10:用Parallel简化Task

Parallel类(简化Task 操作)

标签:

原文地址:http://www.cnblogs.com/hmliang/p/5398285.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!