This commit is contained in:
jiuqianyuan 2025-11-24 03:01:35 +08:00 committed by GitHub
commit 153e2161a3
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 19 additions and 20 deletions

View file

@ -71,28 +71,25 @@ public class DownloaderHelper
} }
}; };
var totalDatetime = DateTime.Now; var lastUpdateTime = DateTime.Now;
var totalSecond = 0;
var hasValue = false; var hasValue = false;
double maxSpeed = 0; double maxSpeed = 0;
await using var downloader = new Downloader.DownloadService(downloadOpt); await using var downloader = new Downloader.DownloadService(downloadOpt);
//downloader.DownloadStarted += (sender, value) =>
//{
// if (progress != null)
// {
// progress.Report("Start download data...");
// }
//};
downloader.DownloadProgressChanged += (sender, value) => downloader.DownloadProgressChanged += (sender, value) =>
{ {
var ts = DateTime.Now - totalDatetime; if (progress != null && value.BytesPerSecondSpeed > 0)
if (progress != null && ts.Seconds > totalSecond)
{ {
hasValue = true; hasValue = true;
totalSecond = ts.Seconds;
if (value.BytesPerSecondSpeed > maxSpeed) if (value.BytesPerSecondSpeed > maxSpeed)
{ {
maxSpeed = value.BytesPerSecondSpeed; maxSpeed = value.BytesPerSecondSpeed;
}
var ts = DateTime.Now - lastUpdateTime;
if (ts.TotalMilliseconds >= 1000)
{
lastUpdateTime = DateTime.Now;
var speed = (maxSpeed / 1000 / 1000).ToString("#0.0"); var speed = (maxSpeed / 1000 / 1000).ToString("#0.0");
progress.Report(speed); progress.Report(speed);
} }
@ -102,8 +99,11 @@ public class DownloaderHelper
{ {
if (progress != null) if (progress != null)
{ {
if (!hasValue && value.Error != null) if (hasValue && maxSpeed > 0)
{ {
var finalSpeed = (maxSpeed / 1000 / 1000).ToString("#0.0");
progress.Report(finalSpeed);
}else if (value.Error != null) {
progress.Report(value.Error?.Message); progress.Report(value.Error?.Message);
} }
} }

View file

@ -335,15 +335,14 @@ public class SpeedtestService(Config config, Func<SpeedTestResult, Task> updateF
using Socket clientSocket = new(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); using Socket clientSocket = new(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
var timer = Stopwatch.StartNew(); var timer = Stopwatch.StartNew();
var result = clientSocket.BeginConnect(endPoint, null, null); using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
if (!result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5))) await clientSocket.ConnectAsync(endPoint, cts.Token).ConfigureAwait(false);
{
throw new TimeoutException("connect timeout (5s): " + url);
}
timer.Stop(); timer.Stop();
responseTime = (int)timer.Elapsed.TotalMilliseconds; responseTime = (int)timer.Elapsed.TotalMilliseconds;
}
clientSocket.EndConnect(result); catch (OperationCanceledException)
{
// 超时情况responseTime保持为-1
} }
catch (Exception ex) catch (Exception ex)
{ {