0

im pretty new to task and async and i get confused on how to cancel the await on var statuss if its taking too long if the ping is successful its instant but if its not itll ping it for about 10 seconds which is not practical when i want to sort through the list as fast as possible

public async void GetServersV2(List<string> ls)
        {
            for (int i = 0; i < ls.Count; i++)
            {
                IMinecraftPinger pinger = new MinecraftPinger(ls[i], (short)port);
                
                try
                {
                    var statuss = await pinger.PingAsync();
                    Console.WriteLineFormatted($"Server: " + ls[i] + " is {0} | {3} online is " + statuss.Players.Online + "/" + statuss.Players.Max + " | " + "{4} is: " + statuss.Version.Name, Color.White, status);
                }
                catch
                {
                    Console.WriteLineFormatted("Server: " + ls[i] + " is {1}", Color.White, status);
                }
            }

        }
  • 3
    Does this answer your question? [Asynchronously wait for Task to complete with timeout](https://stackoverflow.com/questions/4238345/asynchronously-wait-for-taskt-to-complete-with-timeout) – devsmn Dec 21 '20 at 14:16

1 Answers1

1

An option is, to run 2 tasks, the pingerTask and an delayTask, and await the first to win:

var pingTask = pinger.PingAsync(); // start the task, but do not await it
var timeoutTask = Task.Delay(TimeSpan.FromSeconds(10)); // create some timeout task
var winnerTask = await Task.WhenAny(pingTask, timeoutTask); // now await until either the timeoutTask or pingTask finishes

if (winnerTask == pingTask) // if the ping is done before the timeout, then...
{
    var statuss = await pingTask;
}
else
{
     // you run into a timeout
}
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
gofal3
  • 1,213
  • 10
  • 16
  • i solved this by editing the reference where pingasync() was from found the source on github. i change tcp connect to connectasync then added a wait of 1000 milisec and it worked thank you guys for your time to look at my question – Joseph Lindsay Dec 21 '20 at 14:54