I've got a very simple code snippet, to test how to call Task<> method in Main()
using System;
using System.Threading;
using System.Threading.Tasks;
class Program
{
private static async Task<int> F1(int wait = 1)
{
await Task.Run(() => Thread.Sleep(wait));
Console.WriteLine("finish {0}", wait);
return 1;
}
public static async void Main(string[] args)
{
Console.WriteLine("Hello World!");
var task = F1();
int f1 = await task;
Console.WriteLine(f1);
}
}
It doesn't compile because:
(1) F1 is async, so Main() has to be "async".
(2) Compiler says :
error CS5001: Program does not contain a static 'Main' method suitable for an entry point
So if I remove the "async" of Main, compiler will say:
error CS4033: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.
I can either add or remove "async" keyword here. How to make it work? Thanks a lot.
Your Main
method doesn't comply with one of the valid signatures listed here.
You probably want to use this:
public static async Task Main(string[] args)
A Task
needs to be returned, so that the runtime knows when the method is complete; this couldn't be determined with void
.
The compiler achieves this by generating a synthetic entry point:
private static void $GeneratedMain(string[] args) =>
Main(args).GetAwaiter().GetResult();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With