J'ai un extrait de code très simple, pour tester comment appeler la méthode Task<> dans 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);
}
}
Il ne compile pas parce que :
(1) F1 est asynchrone, donc Main() doit être "asynchrone".
(2) Le compilateur dit :
error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Ainsi, si je supprime le "async" de Main, le compilateur dira :
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'.
Je peux ajouter ou supprimer le mot-clé "async" ici. Comment faire pour que cela fonctionne ? Merci beaucoup.