C
C#17mo ago
Uchuu

❔ need some advice

private async Task<Result> ReceiveStartCommands()
{
var commands = new List<IInputCommand>();

foreach (var trainer in Scene.Trainers)
{
var command = await InputProvider.GetInput(trainer.Id);
commands.Add(command);
}

// ReSharper disable once ConvertIfStatementToReturnStatement
if (!commands.All(command => command is BattleStartCommand))
{
return new InvalidOperationError("Failed to start battle because Start Commands were not received from all trainers.");
}

return Result.FromSuccess();
}
private async Task<Result> ReceiveStartCommands()
{
var commands = new List<IInputCommand>();

foreach (var trainer in Scene.Trainers)
{
var command = await InputProvider.GetInput(trainer.Id);
commands.Add(command);
}

// ReSharper disable once ConvertIfStatementToReturnStatement
if (!commands.All(command => command is BattleStartCommand))
{
return new InvalidOperationError("Failed to start battle because Start Commands were not received from all trainers.");
}

return Result.FromSuccess();
}
I have this code that receives the start commands from every player using an input provider. However, this means that the second player must wait for the first to send their command. What is the best practice so can I make it so these commands can be received from both players without having to wait
5 Replies
Uchuu
UchuuOP17mo ago
Would it be as simple as?
trainers.Select(trainer => InputProvider.GetInput(trainer.Id));
var commands = await Task.WhenAll(inputTasks);
trainers.Select(trainer => InputProvider.GetInput(trainer.Id));
var commands = await Task.WhenAll(inputTasks);
Frostshoxx
Frostshoxx17mo ago
if you ever comes across a situation where you would have a for loop with await in it. Change that to add task from each loop into a list, then convert to array and throw it into await Task.WhenAll(tasks);
Frostshoxx
Frostshoxx17mo ago
Stack Overflow
Using async/await for multiple tasks
I'm using an API client that is completely asynchrounous, that is, each operation either returns Task or Task<T>, e.g: static async Task DoSomething(int siteId, int postId, IBlogClient clien...
Frostshoxx
Frostshoxx17mo ago
Although, it might be worth looking into IAsyncEnumerable while you're at it.
Accord
Accord17mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server