Using ‘async’ in a console application in C# [duplicate]

I have this simple code:

public static async Task<int> SumTwoOperationsAsync()
{
    var firstTask = GetOperationOneAsync();
    var secondTask = GetOperationTwoAsync();
    return await firstTask + await secondTask;
}


private async Task<int> GetOperationOneAsync()
{
    await Task.Delay(500); // Just to simulate an operation taking time
    return 10;
}

private async Task<int> GetOperationTwoAsync()
{
    await Task.Delay(100); // Just to simulate an operation taking time
    return 5;
}

Great. This compiles.

But let’s say I have a console application and I want to run the code above (calling SumTwoOperationsAsync()).

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

But I’ve read that (when using sync) I have to sync all the way up and down:

Does this mean that my Main function should be marked as async?

Well, it can’t be because there is a compilation error:

an entry point cannot be marked with the ‘async’ modifier

If I understand the async stuff , the thread will enter the Main function → SumTwoOperationsAsync → will call both functions and will be out. But until the SumTwoOperationsAsync

What am I missing?

4 Answers
4

Leave a Comment