Create method which will be executed by async tasks.
private static double Calculate(int value1, int value2) { Thread.Sleep(10000); // simulate busy return value1 + value2; }
Create summary method which will operate on results from async tasks.
private static double SummaryResultsFromAsyncTasks(List<Task<double>> asyncTasksList) { double summaryResult = 0; foreach (Task<double> asyncTask in asyncTasksList) { summaryResult = summaryResult + asyncTask.Result; } return summaryResult; }
Create method which execute async tasks and summary method.
private static double SummaryTasksResults() { List<Task<double>> asyncTasksList = new List<Task<double>>(); for (int i = 1; i <= 3; i++) { Task<double> asyncTask = Task<double>.Factory.StartNew(() => Calculate(1, i)); asyncTasksList.Add(asyncTask); } Task<double> summaryTask = Task<double>.Factory.ContinueWhenAll(asyncTasksList.ToArray(), summaryResult => SummaryResultsFromAsyncTasks(asyncTasksList)); summaryTask.Wait(); return summaryTask.Result; }
Main method execute SummaryTasksResults and return finally result.
private static void Main(string[] args) { double summaryValue = SummaryTasksResults(); }
Brak komentarzy:
Prześlij komentarz