poniedziałek, 10 sierpnia 2015

Return values from async tasks when all tasks finished

Example of using async tasks to return value from method "Calculate". When all tasks finished execute method "SummaryResultsFromAsyncTasks" which sum results from async tasks.

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<doubleasyncTask 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