ToListAsync

CSharp · Console

/Program.cs

using System;
using System.Diagnostics;
using System.Linq;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Example
{
    public static class ExtensionMethods
    {
        static public async Task<List<T>> ToListAsync<T>(this IEnumerable<Task<T>> This)
        {
            var tasks = This.ToList();     //Force LINQ to iterate and create all the tasks. Tasks always start when created.
            var results = new List<T>();   //Create a list to hold the results (not the tasks)
            foreach (var item in tasks)
            {
                results.Add(await item);   //Await the result for each task and add to results list
            }
            return results;
        }
    }




    public class Program
    {
        private const int MillisecondsPerTask = 50;
        private const int TasksPerTest = 10;
        private const int TestIterations = 3;
		
        public static object DoSomethingExpensive(int id)
        {
            Console.WriteLine("Handling task {0} synchronously", id);
            System.Threading.Thread.Sleep(MillisecondsPerTask);
            Console.WriteLine("Done handling task {0} synchronously", id);
            return null;
        }

        public static async Task<object> DoSomethingExpensiveAsync(int id)
        {
            Console.WriteLine("Handling task {0} asynchronously", id);
            await Task.Delay(MillisecondsPerTask);
            Console.WriteLine("Done handling task {0} asynchronously", id);
            return null;
        }

        public static void TestBlocking()
        {
            var pages = Enumerable.Range(0, TasksPerTest).Select
                ( 
                    n => DoSomethingExpensive(n) 
                )
                .ToList();
        }

        public static async Task TestAsync()
        {
            var pages = await Enumerable.Range(0, TasksPerTest).Select
                ( 
                    async n => await DoSomethingExpensiveAsync(n) 
                )
                .ToListAsync();
        }
		
        public static async Task MainAsync()
        {
            //Run them once to prime any buffers or paging
            TestBlocking();
            await TestAsync();

            //Test and take timings
            for (int i = 0; i < TestIterations; i++)
            {
                var sw1 = new Stopwatch();
                sw1.Start();
                TestBlocking();
                sw1.Stop();

                var sw2 = new Stopwatch();
                sw2.Start();
                await TestAsync();
                sw2.Stop();
                Console.WriteLine("Sync:  {0:0000} milliseconds\r\nAsync: {1:0000} milliseconds", sw1.ElapsedMilliseconds, sw2.ElapsedMilliseconds);
            }
        }

    
        public static void Main()
        {
            MainAsync().GetAwaiter().GetResult();
        }
    }
}
;