1. 程式人生 > >Parallel.For with await and wait()

Parallel.For with await and wait()

 

        static void Parallel2()
        {
            ParallelLoopResult result = Parallel.For(1, 9, i =>
            {
                Log($"S:{i} ");
                Task.Delay(10).Wait();
                Log($"E:{i} ");
            });
            WriteLine($"IsCompleted:{result.IsCompleted}
"); } static void Parallel1WithAsync() { ParallelLoopResult result = Parallel.For(1, 9, async i => { Log($"S:{i} "); await Task.Delay(10); Log($"E:{i} "); }); WriteLine($"IsCompleted:{result.IsCompleted}
"); } static void Log(string prefix) { WriteLine($"{prefix}, taks:{Task.CurrentId}, thread:{Thread.CurrentThread.ManagedThreadId}"); }

 


Task.Delay(10).Wait(); Result

S:1 , taks:3, thread:1
S:3 , taks:4, thread:4
S:5 , taks:6, thread:5
S:7 , taks:9, thread:6
E:7 , taks:9, thread:6
S:8 , taks:13, thread:6
E:3 , taks:4, thread:4
S:4 , taks:15, thread:4
E:1 , taks:3, thread:1
S:2 , taks:3, thread:1
E:5 , taks:6, thread:5
S:6 , taks:11, thread:8
E:2 , taks:3, thread:1
E:8 , taks:13, thread:6
E:4 , taks:15, thread:4
E:6 , taks:11, thread:8
IsCompleted:True

await Task.Delay(10)result:

S:1 , taks:3, thread:1
S:5 , taks:5, thread:5
S:6 , taks:5, thread:5
S:8 , taks:5, thread:5
S:4 , taks:5, thread:5
S:3 , taks:4, thread:3
S:7 , taks:7, thread:6
S:2 , taks:3, thread:1
IsCompleted:True
E:3 , taks:, thread:6
E:6 , taks:, thread:6
E:5 , taks:, thread:6
E:1 , taks:, thread:6
E:4 , taks:, thread:5
E:2 , taks:, thread:6
E:7 , taks:, thread:5
E:8 , taks:, thread:3