Search⌘ K
AI Features

Solution: Fastest Server Matchmaking

Explore how to use asynchronous programming in C# to identify the fastest server among multiple tasks. Understand how Task.WhenAny works to await the first completed task and retrieve its result. This lesson guides you through building responsive, efficient matchmaking logic with practical code examples.

We'll cover the following...
C# 14.0
using System.Threading.Tasks;
namespace Multiplayer;
public class Matchmaker
{
public async Task<string> FindFastestServerAsync()
{
Task<string> usTask = PingServerAsync("US-East", 700);
Task<string> euTask = PingServerAsync("Europe", 500);
Task<string> asiaTask = PingServerAsync("Asia", 550);
Task<string> winningTask = await Task.WhenAny(usTask, euTask, asiaTask);
string fastestServer = await winningTask;
return fastestServer;
}
private async Task<string> PingServerAsync(string region, int delayInMilliseconds)
{
await Task.Delay(delayInMilliseconds);
return region;
}
}
...