C# Parallel 使用

  ParallelLoopResult result = Parallel.For(0, 10, i =>
            {
                Console.WriteLine("{0}, task: {1}, thread: {2}", i,
                    Task.CurrentId, Thread.CurrentThread.ManagedThreadId);
                Thread.Sleep(10);
            });
           
            Console.WriteLine("Is completed: {0}, run time is {1}", result.IsCompleted, watch.ElapsedMilliseconds);

 

 async 、 await 使用

ParallelLoopResult result1 = 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}, run time is {1}", result.IsCompleted, watch.ElapsedMilliseconds);

条件退出

            ParallelLoopResult result = Parallel.For(10, 40, async (i, s) =>
            {
                Console.WriteLine("i: {0} task: {1}", i, Task.CurrentId);
                Thread.Sleep(10); // await Task.Delay(10);
                if (i > 15)
                    s.Break();
            });

            Console.WriteLine("Is completed: {0}", result.IsCompleted);
            if (!result.IsCompleted)
                Console.WriteLine("lowest break iteration: {0}", result.LowestBreakIteration);

 

 For<T> 使用

  Parallel.For<string>(0, 20, () =>
                {
                    Console.WriteLine("init thread {0}, task {1}", Thread.CurrentThread.ManagedThreadId, Task.CurrentId);
                    return String.Format("t{0}", Thread.CurrentThread.ManagedThreadId);
                }, (i, s, str) =>
                {
                    Console.WriteLine("body i {0} str1 {1} thread {2} task {3}", i, str,
                    Thread.CurrentThread.ManagedThreadId, Task.CurrentId);
                    Thread.Sleep(10);
                    return String.Format("i {0}", i);
                }, s =>
                {
                    Console.WriteLine("finally {0}", s);
                });

ForEach<T> 使用

            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, (i, s, l) =>
            {

                Console.WriteLine("{0}, {1}", i, l);
            });

Invoke 方法组调用

  Parallel.Invoke(Foo, Bar);

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

 

posted @ 2016-11-04 14:13  指间的徘徊  阅读(2239)  评论(0编辑  收藏  举报