In my command line program, the user can execute either two asynchronous functions (selection 1) or two synchronous functions (selection 2) via a selection loop. Unfortunately, the execution of the asynchronous functions behaves exactly the same as the synchronous functions: The selection loop freezes until the tasks are finished. Maybe I have a wrong understanding of await but shouldn't it ensure that the execution of the program continues. I now firmly expect the "Hello World" output to be displayed while the tasks are still busy. Where is my error in thinking?
await main();
static async Task main()
{
string input="start";
while(input!="exit"){
Console.WriteLine("choose an option:");
Console.WriteLine("1 asynchrone");
Console.WriteLine("2 synchrone");
Console.WriteLine("exit.");
input=Console.ReadLine();
switch(input){
case "1":await startTaskAsync();Console.WriteLine("Hello World");break;
case "2":startTaskSync(); break;
case "exit":input="exit"; break;
default:input="exit";break;
}
}
}
static async Task startTaskAsync(){
var FrogTask=startFrogAsync();
var MouseTask=startMouseAsync();
List<Task> allTask=new List<Task>(){FrogTask,MouseTask};
Task.WaitAll(MouseTask,FrogTask);
Console.WriteLine(FrogTask.Result);
Console.WriteLine(MouseTask.Result);
}
static void startTaskSync(){
string result1=startFrogSync();
string result2=startMouseSync();
Console.WriteLine(result1);
Console.WriteLine(result2);
}
static async Task<string> startMouseAsync(){
string result ="startMouseAsync completed";
Thread.Sleep(2000);
return result;
}
static async Task<string> startFrogAsync(){
string result ="startFrogAsync completed";
Thread.Sleep(10000);
return result;
}
static string startMouseSync(){
string result ="startMouseSync completed";
Thread.Sleep(2000);
return result;
}
static string startFrogSync(){
string result ="startFrogSync completed";
Thread.Sleep(10000);
return result;
}