首页 > 编程语言 > 详细

线程、任务和同步学习笔记(四)

时间:2016-06-01 08:04:03      阅读:284      评论:0      收藏:0      [点我收藏+]

1、抽象线程类Parallel的For和ForEach方法可以多次调用同一个方法。Parallel类的Invoke方法允许同时调用不同的方法。

 1 using System;
 2 using System.Threading;
 3 using System.Threading.Tasks;
 4 
 5 class Program
 6 {
 7     static void Main(string[] args)
 8     {
 9         ParallelLoopResult result = Parallel.For(0, 10, i =>
10         {
11             Console.WriteLine("{0}, task: {1}, thread: {2}", i, Task.CurrentId, Thread.CurrentThread.ManagedThreadId);
12             Thread.Sleep(10);
13         });
14         Console.WriteLine(result);
15         Console.WriteLine(result.IsCompleted);
16     }
17 }

运行结果:

技术分享

2、循环可以中断,中断的方式是使用ParallelLoopState的Break方法。

 1 using System;
 2 using System.Threading;
 3 using System.Threading.Tasks;
 4 
 5 class Program
 6 {
 7     static void Main(string[] args)
 8     {
 9         ParallelLoopResult result = Parallel.For(0, 30, (int i, ParallelLoopState state) =>
10         {
11             Console.WriteLine("{0}, task: {1}, thread: {2}", i, Task.CurrentId, Thread.CurrentThread.ManagedThreadId);
12             Thread.Sleep(10);
13             if (i > 10)
14             {
15                 state.Break();
16             }
17         });
18         Console.WriteLine(result.IsCompleted);
19         Console.WriteLine("Lowest break iteration: {0}.", result.LowestBreakIteration);
20     }
21 }

运行结果:

技术分享

从上图所示的运行结果可以看出,程序并不能保证循环变量 i 的值都满足条件。

线程、任务和同步学习笔记(四)

原文:http://www.cnblogs.com/luckymonkey/p/5548308.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!