Home > Software engineering >  'Async' / 'Await' not working as expected in C#
'Async' / 'Await' not working as expected in C#

Time:10-16

im new to C# and i was trying to figure out async and await . for practice i was trying to start method 1 in which method 2 is called twice . method 2 takes a value and increases it by 1 each 200 ms . instead of running method 2 the program ends after the first line of method 1 .

    static void Main(string[] args)
    {
        Method1();
    }

    static int Method2(int x)
    {
        for (int i = 0; i < 10; i  )
        {
            x  = 1;
            Console.WriteLine(x);
            Thread.Sleep(200);
        }
        Console.WriteLine("final"   " "   x   " "   Thread.CurrentThread.ManagedThreadId);
        return x;

    }
    static async Task Method1()
    {
        Console.WriteLine("1 running");
        int result1 = await Task.Run(() => Method2(0));
        int result2 = await Task.Run(() => Method2(result1));
        Thread.Sleep(1000);
        Console.WriteLine("result "   result2 * 2);
    }

what am i doing wrong here ?

CodePudding user response:

When calling Method() you aren't waiting on it. It returns a task object that is not acted upon, and then Main() dutifully returns, which ends the program.

You can do this in Main():

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

Or use async Main() instead:

public static async Task Main() {
    await Method1();
}
  • Related