본문 바로가기

프로그래밍언어/C#

[C#] 동시성 프로그래밍_Task.WhenAll

- 모든 작업의 완료를 대기하고 싶을 때 사용

- 다수의 작업을 전달받고 제공된 모든 작업이 완료될 때 까지 스레드를 블로킹 시킨다.

 public class AsyncTest
    {

        public static string Run()
        {
            StringBuilder sb = new StringBuilder();
            for (var i = 0; i<=1000; i++) {
                sb.AppendLine(String.Format("Task {0}", i));      
            };

            return  sb.ToString(); //problem here
        }

        public static async void WaitWhanAllTask() {
            Task<string> task1 = Task.FromResult("Task1 Start");
            Task<string> task2 = Task.FromResult("Task2 Start");
            Task<string> task3 = Task.FromResult(AsyncTest.Run());

            string[] results = await Task.WhenAll(task1, task2, task3);

            Console.WriteLine(string.Join(",", results));
        }

    }

- 결과