Javad-M
Javad-M

Reputation: 604

Asynchronous method does not work well in Console application

I am using the following code and want to test the parallel programming, but there are some problems.

using System;
using System.Threading.Tasks;

namespace DemoParallelApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("*** Main Method Start ***");
            Operation();
            Console.WriteLine("*** Main Method End ***");
        }
        static void Operation()
        {
            Console.WriteLine("*** Operation Method Start ***");
            var task1 = Delay(5000);
            Console.WriteLine("*** Operation Method End ***");
        }

        static async Task<int> Delay(int ms)
        {
            Console.WriteLine($"Start {ms}(ms) Delay");
            await Task.Delay(ms);
            Console.WriteLine($"End {ms}(ms) Delay");
            return ms;
        }
    }
}

The result is like this:

*** Main Method Start ***
*** Operation Method Start
*** Start 5000(ms) Delay
*** Operation Method End ***
*** Main Method End ***

But I think it should be like this one:

*** Main Method Start ***
*** Operation Method Start ***
Start 5000(ms) Delay
*** Operation Method End ***
*** Main Method End ***
End 5000(ms) Delay

What is wrong with it?

Upvotes: 0

Views: 350

Answers (2)

Guru Stron
Guru Stron

Reputation: 143493

Your program finishes before the Wait and terminates (including the "wait" method). You need to await the task returned by Delay somewhere. To have desired output you can do it like that, for example (using C# 7.1 async Main feature):

class Program
{
    static async Task Main(string[] args)
    {
        Console.WriteLine("*** Main Method Start ***");
        var t = Operation();
        Console.WriteLine("*** Main Method End ***");
        await t;
    }
    static Task Operation()
    {
        Console.WriteLine("*** Operation Method Start ***");
         var task1 = Delay(5000);
        Console.WriteLine("*** Operation Method End ***");
         return task1 ;
    }

    static async Task<int> Delay(int ms)
    {
        Console.WriteLine($"Start {ms}(ms) Delay");
        await Task.Delay(ms);
        Console.WriteLine($"End {ms}(ms) Delay");
        return ms;
    }
}

Upvotes: 4

Misha Zaslavsky
Misha Zaslavsky

Reputation: 9712

You need to await the Delay:

static async Task Operation()
{
    Console.WriteLine("*** Operation Method Start ***");
    var task1 = await Delay(5000);
    Console.WriteLine("*** Operation Method End ***");
}

And call Operation with await as well, in your case as the main method is not asyncable you can do it this way:

Task.Run(() => Operation()).GetAwaiter().GetResult();

Upvotes: 1

Related Questions