How to asynchronously run multiple methods in C#

1 Answer

0 votes
using System;
using System.Threading.Tasks;

class Program
{
    static void Main()
    {
        // Call async method 13 times.
        for (int i = 0; i < 13; i++) {
            RunMethods(i);
        }
        Console.ReadLine();
    }
    
    static async void RunMethods(int val) {
        int result = await Task.Run(() => Calc(val))
                    .ContinueWith(task => Plus10000(task));
        Console.WriteLine("RunMethods result: " + result);
    }
    
    static int Calc(int val) {
        int sum = 0;
        for (int i = 0; i < val; i++) {
            sum += (int)Math.Pow(i, 2);
        }
        return sum;
    }
    
    static int Plus10000(Task<int> task) {
        return task.Result + 10000;
    }
}




/*
run:

RunMethods result: 10005
RunMethods result: 10001
RunMethods result: 10140
RunMethods result: 10000
RunMethods result: 10204
RunMethods result: 10385
RunMethods result: 10285
RunMethods result: 10091
RunMethods result: 10506
RunMethods result: 10014
RunMethods result: 10030
RunMethods result: 10000
RunMethods result: 10055

*/

 



answered Mar 17, 2023 by avibootz

Related questions

1 answer 347 views
1 answer 122 views
122 views asked Oct 17, 2023 by avibootz
1 answer 164 views
164 views asked Oct 14, 2023 by avibootz
1 answer 131 views
131 views asked Oct 13, 2023 by avibootz
1 answer 121 views
121 views asked Sep 26, 2023 by avibootz
1 answer 115 views
115 views asked Sep 23, 2023 by avibootz
1 answer 137 views
137 views asked Sep 22, 2023 by avibootz
...