Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

'Async' / 'Await' not working as expected in C#

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading