/// <inheritdoc /> public int TestServerLatency(Server server, int retryCount = 3, CancellationToken cancellationToken = default) { var latencyUri = CreateTestUrl(server, "latency.txt"); var timer = new Stopwatch(); using (var client = new SpeedTestHttpClient()) { for (var i = 0; i < retryCount; i++) { string testString; try { timer.Start(); testString = client.GetStringAsync(latencyUri, cancellationToken).ConfigureAwait(false).GetAwaiter().GetResult(); } catch (Exception) { continue; } finally { timer.Stop(); } if (!testString.StartsWith("test=test")) { throw new InvalidOperationException("Server returned incorrect test string for latency.txt"); } } return((int)timer.ElapsedMilliseconds / retryCount); } }
/// <summary> /// Test latency (ping) to server /// </summary> /// <returns>Latency in milliseconds (ms)</returns> public async Task <int> TestServerLatencyAsync(Server server, int retryCount = 3) { var latencyUri = CreateTestUrl(server, "latency.txt"); var timer = new Stopwatch(); using (var client = new SpeedTestHttpClient()) { for (var i = 0; i < retryCount; i++) { string testString; try { timer.Start(); testString = await client.GetStringAsync(latencyUri).ConfigureAwait(false); } catch (WebException) { continue; } finally { timer.Stop(); } if (!testString.StartsWith("test=test")) { throw new InvalidOperationException("Server returned incorrect test string for latency.txt"); } } } return((int)timer.ElapsedMilliseconds / retryCount); }