Parallel类(简化Task 操作)

时间:2022-11-13 20:58:21

Parallel类

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

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

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

Parallel类(简化Task 操作)

2.提前停止Parallel.For

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

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

Parallel类(简化Task 操作)

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); });

Parallel类(简化Task 操作)

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

    static void ParallelInvoke()
{
Parallel.Invoke(Foo, Bar);
} static void Foo()
{
Console.WriteLine("foo");
} static void Bar()
{
Console.WriteLine("bar");
}

Parallel类(简化Task 操作)

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