I am new to asynchronous programming with the async
modifier. I am trying to figure out how to make sure that my Main
method of a console application actually runs asynchronously.
class Program
{
static void Main(string[] args)
{
Bootstrapper bs = new Bootstrapper();
var list = bs.GetList();
}
}
public class Bootstrapper {
public async Task<List<TvChannel>> GetList()
{
GetPrograms pro = new GetPrograms();
return await pro.DownloadTvChannels();
}
}
I know this is not running asynchronously from "the top." Since it is not possible to specify the async
modifier on the Main
method, how can I run code within main
asynchronously?
In Main try changing the call to GetList to:
You can do this without needing external libraries also by doing the following:
When the C# 5 CTP was introduced, you certainly could mark Main with
async
... although it was generally not a good idea to do so. I believe this was changed by the release of VS 2013 to become an error.Unless you've started any other foreground threads, your program will exit when
Main
completes, even if it's started some background work.What are you really trying to do? Note that your
GetList()
method really doesn't need to be async at the moment - it's adding an extra layer for no real reason. It's logically equivalent to (but more complicated than):C# 7.1 (using vs 2017 update 3) introduces async main
You can write:
For more details C# 7 Series, Part 2: Async Main
Update:
You may get a compilation error:
This error is due to that vs2017.3 is configured by default as c#7.0 not c#7.1.
You should explicitly modify the setting of your project to set c#7.1 features.
You can set c#7.1 by two methods:
Method 1: Using the project settings window:
Method2: Modify PropertyGroup of .csproj manually
Add this property:
example:
If you're using C# 7.1 or later, go with the nawfal's answer and just change the return type of your Main method to
Task
orTask<int>
. If you are not:async Task MainAsync
like Johan said..GetAwaiter().GetResult()
to catch the underlying exception like do0g said.CTRL+C
should terminate the process immediately. (Thanks binki!)OperationCancelledException
- return an appropriate error code.The final code looks like:
Haven't needed this much yet, but when I've used console application for Quick tests and required async I've just solved it like this: