Async and await in C# - Asynchronous programming in C#, basic example using Console


Back to learning
Created: 16/10/2019

Async and await in C# - Asynchronous programming in C#, basic example using Console


class Program
    {
        static void Main(string[] args)
        {
            List<Task> lst = new List<Task>();

            lst.Add(GetFactorialAsync(1, 10));
            lst.Add(GetFactorialAsync(2, 6));
            lst.Add(GetFactorialAsync(3, 7));
            lst.Add(GetFactorialAsync(4, 8));
            lst.Add(GetFactorialAsync(5, 9));

            Task.WaitAll(lst.ToArray());

            Console.WriteLine("End");

            Console.ReadKey();
        }

        public static async Task GetFactorialAsync(int numero, int valor)
        {
            long resultado = 1;
            await Task.Run(() =>
            {
                for (int i = 1; i <= valor; i++)
                {
                    resultado = resultado * i;
                }
            });

            Console.WriteLine("Thread: " + numero.ToString() + ", "+ resultado.ToString());
        }
    }



Explanation, basically we will lounch 5 times the same Method to calculate the factorial of different numbers, but asyncroniously. If you excecute this Console Application several times you will see that they will change the order of excecution. Pay attention that at the end of our app i placed WaitAll, this line will wait till all the calculations are compleated. And also in this particular case pay attention to LONG type, factorial numbers can be pretty big, so you maigh need somthing bigger than integer.