Optimize file download

pull/3234/head
2dust 2023-02-09 10:54:31 +08:00
parent d014724a2d
commit 7eb869ab1d
2 changed files with 73 additions and 11 deletions

View File

@ -1,4 +1,5 @@
using Downloader;
using System.IO;
using System.Net;
namespace v2rayN.Base
@ -85,5 +86,72 @@ namespace v2rayN.Base
downloader = null;
downloadOpt = null;
}
public async Task DownloadFileAsync(IWebProxy webProxy, string url, string fileName, IProgress<double> progress, int timeout)
{
if (string.IsNullOrEmpty(url))
{
throw new ArgumentNullException("url");
}
if (string.IsNullOrEmpty(fileName))
{
throw new ArgumentNullException("fileName");
}
if (File.Exists(fileName))
{
File.Delete(fileName);
}
var cancellationToken = new CancellationTokenSource();
cancellationToken.CancelAfter(timeout * 1000);
var downloadOpt = new DownloadConfiguration()
{
Timeout = timeout * 1000,
MaxTryAgainOnFailover = 2,
RequestConfiguration =
{
Timeout= timeout * 1000,
Proxy = webProxy
}
};
var progressPercentage = 0;
var hasValue = false;
var downloader = new DownloadService(downloadOpt);
downloader.DownloadStarted += (sender, value) =>
{
if (progress != null)
{
progress.Report(0);
}
};
downloader.DownloadProgressChanged += (sender, value) =>
{
hasValue = true;
var percent = (int)value.ProgressPercentage;// Convert.ToInt32((totalRead * 1d) / (total * 1d) * 100);
if (progressPercentage != percent && percent % 10 == 0)
{
progressPercentage = percent;
progress.Report(percent);
}
};
downloader.DownloadFileCompleted += (sender, value) =>
{
if (progress != null)
{
if (hasValue && value.Error == null)
{
progress.Report(101);
}
}
};
await downloader.DownloadFileTaskAsync(url, fileName, cancellationToken: cancellationToken.Token);
downloader.Dispose();
downloader = null;
downloadOpt = null;
}
}
}

View File

@ -70,11 +70,6 @@ namespace v2rayN.Handler
Utils.SetSecurityProtocol(LazyConfig.Instance.GetConfig().enableSecurityProtocolTls13);
UpdateCompleted?.Invoke(this, new ResultEventArgs(false, ResUI.Downloading));
var client = new HttpClient(new SocketsHttpHandler()
{
Proxy = GetWebProxy(blProxy)
});
var progress = new Progress<double>();
progress.ProgressChanged += (sender, value) =>
{
@ -85,12 +80,11 @@ namespace v2rayN.Handler
}
};
var cancellationToken = new CancellationTokenSource();
_ = HttpClientHelper.GetInstance().DownloadFileAsync(client,
url,
Utils.GetTempPath(Utils.GetDownloadFileName(url)),
progress,
cancellationToken.Token);
_ = DownloaderHelper.Instance.DownloadFileAsync(GetWebProxy(blProxy),
url,
Utils.GetTempPath(Utils.GetDownloadFileName(url)),
progress,
downloadTimeout);
}
catch (Exception ex)
{