Qualcuno può chiarire questo esempio, che ovviamente, non funziona:metodo C# Async chiamare fino alla principale
class Program
{
static void Main(string[] args)//main cant' be async
{
int res = test();//I must put await here
Console.WriteLine("END");
}
public async static Task<int> test()
{ //why can't I make it just: public int test()??
int a1, a2, a3, a4;
a1 = await GetNumber1();
a2 = await GetNumber2();
a3 = await GetNumber3();
a4 = a1 + a2 + a3;
return a4;
}
public static async Task<int> GetNumber1()
{
await Task.Run(() =>
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine("GetNumber1");
System.Threading.Thread.Sleep(100);
}
});
return 1;
}
che sto cercando di "raccogliere" i valori ottenuti con metodi GenNumberX utilizzando "attendono". Mi piacerebbe rendere il metodo "test" non asincrono in qualche modo. Non capisco perché il test deve essere asincrono quando sto usando attendi per ottenere un valore. Questo esempio mi fa scrivere asincronamente su ogni metodo in cui utilizzo async, e quando eseguo il drill su Main, non riesco a renderlo asincrono?
come scrivere esempio del mondo reale:
public bool ReserveAHolliday()
{
bool hotelOK = await ReserveAHotel();//HTTP async request
bool flightOK = await ReserveFlight();////HTTP async request
bool result = hotelOK && flightOK;
return result;
}
Come rendere metodo ReserveAHolliday sincrono? Mi manca qualcosa o non capisco l'uso del meccanismo di attesa asincrono?
A un certo punto è necessario avviare un asynctask da un metodo sincrono. Se vuoi sparare, chiamalo semplicemente (chiamato anche vuoti asincroni, accendi e dimentichi), o usa 'test(). Wait()' che attenderà l'attività in modo sincrono. – FrankerZ