1.Parallel类
1.1介绍
Parallel类是对线程的一个很好的抽象,提供了数据和任务的并行性。
1.2用Parallel.For()方法循环
并行的多次运行同一个任务
int i = 1; Parallel.For(1, 100, j => { Console.WriteLine(i++); }); Console.ReadKey();
1.3用Parallel.Foreach()方法循环
string[] data = { "a","b","c","d","e","f"}; Parallel.ForEach(data, item => { Console.WriteLine(item); }); Console.WriteLine("completed"); Console.ReadKey();
1.4通过Parallel.Invoke()方法并行运行多个任务
Parallel.Invoke(() => { Console.WriteLine(1); }, () => { Console.WriteLine(2); }); Console.ReadKey();
2.Task类
2.1介绍
Task类可以更好的控制并行动作,连续的执行多个任务,任务之间可以建立依赖关系。
2.2启动任务
//方法1 Task task0=Task.Factory.StartNew(() => { Console.WriteLine("用Task类的静态属性访问TaskFactory"); }); //方法2 Task task1 = new Task(() => { Console.WriteLine("Task的默认构造方法"); }); task1.Start(); //方法3 Task task2 = new TaskFactory().StartNew(() => { Console.WriteLine("任务工厂创建Task的实例"); }); Console.WriteLine("主线程结束"); Console.ReadKey();
2.3同步任务
Task task = new Task(() => { Console.WriteLine("Task1的默认构造方法"); }); task.RunSynchronously(); Task task1 = new Task(() => { Console.WriteLine("Task2的默认构造方法"); }); task1.RunSynchronously(); Task task2 = new Task(() => { Console.WriteLine("Task3的默认构造方法"); }); task2.RunSynchronously(); Console.WriteLine("主线程结束"); Console.ReadKey();
2.4Future---任务的结果
任务结束时,它可以把有用的状态信息写到共享对象中
static Tuple<int, int,int> TaskWithResult(object division) { Tuple<int, int> div = (Tuple<int, int>)division; int result = div.Item1 / div.Item2; int reminder = div.Item1 % div.Item2; int r = div.Item1 + div.Item2; Console.WriteLine("task creates a result"); return Tuple.Create<int, int,int>(result, reminder, r); } static void Main(string[] args) { var t1 = new Task<Tuple<int, int,int>>(TaskWithResult,Tuple.Create<int,int>(10,3)); t1.Start(); Console.WriteLine(t1.Result); t1.Wait(); Console.WriteLine("result from task:{0},{1},{2}",t1.Result.Item1,t1.Result.Item2,t1.Result.Item3); Console.ReadKey(); }
2.5连续的任务
static void DoFirstTask(){ Console.WriteLine("DoFirstTask"); } static void DoSecondTask(Task task){ Console.WriteLine("之前的任务已结束,任务ID:"+task.Id); Console.WriteLine("DoSecondTask"); } static void Main(string[] args) { Task task1 = new Task(DoFirstTask); Task task2 = task1.ContinueWith(DoSecondTask); task1.Start(); Console.ReadKey(); }
时间: 2024-10-14 11:13:25