I'm coding a server-client game. There is a moment were some events happen in the game that requires asking the players (clients) what they want to do. This is how I tried that:
TaskCompletionSource<string> QuestionManager;
public async Task GoThroughtEvents(){
myEvents.ForEach( async ev => {
switch(ev){
case eventOfTypeA:
await DoTypeA();
break;
//other similar cases
}
});
}
public async Task DoTypeA(){
string answer = await AskPlayer();
//I want it to stay here until the response comes
//instead it enters in the foreach with the next iteration
//and when the response comes it contines from here
//but at the end the events are processed in the wrong order
// do stuff with the answer, potentially more questions.
}
public async Task<string> AskPlayer()
{
QuestionManager= new TaskCompletionSource<string>();
return TaskCompletionSource.Task;
}
public void ProcessAnswerFromUser(string response)
{
QuestionManager.SetResult(response);
}
I want the events to happen one by one in the correct order, with the players being asked in order, and the code to wait for these responses before continuing.
But instead, the code halts on the await, but a new "?thread?" starts with the next loop of the foreach, and the next event is processed before this one is finished.