我正在使用 httpClient.GetAsync 异步查询 10 个网络请求,并且在 10 个请求之一完成下载后,我正在使用 Task.Any 处理数据
问题是,每个 10 个请求大约需要 2-3 秒来下载和使用 Task.Any 意味着我的应用程序正在同时下载 10 个网络请求
如果我的连接带宽很慢,则数据处理会延迟
解决方案是下载一些请求,例如 10 个请求中的 2 个,并休眠其他 8 个请求。然后在处理第一个 webrequest 时继续唤醒其余的 webrequest。
我现在不知道该怎么做,我的代码看起来像这样
private async void OnLaunchClick(object sender, RoutedEventArgs e)
{
var quotesTask = new List<Task<IEnumerable<Symbol>>>();
for (int i = 0; i < userInput.Symbols.Count(); i = i + SYMBOLS_PAGINATION_PER_REQUEST)
{
var input = new UserInput(userInput.Symbols.Skip(i).Take(SYMBOLS_PAGINATION_PER_REQUEST), userInput.StartDate, userInput.EndDate, userInput.Interval);
quotesTask.Add(quotesQuery.GetSymbolsInternal(input, _cts.Token));
}
while (quotesTask.Count > 0)
{
Task<IEnumerable<Symbol>> quotesFinishedTask = await Task.WhenAny(quotesTask);
quotesTask.Remove(quotesFinishedTask);
// Update UI
}
}
public async Task<IEnumerable<Symbol>> GetSymbolsInternal(UserInput filteredInput, CancellationToken token)
{
if (filteredInput == null) throw new ArgumentNullException("filteredInput");
string url = BuildUrl(filteredInput);
logger.Debug(string.Format("Start downloading quotes: {0}\n{1}",
filteredInput.Symbols.Select(a => a.Name).Join(","),
url));
string content = await _webRequest.GetData(url, token).ConfigureAwait(false);
logger.Debug(string.Format("End downloading quotes: {0}", filteredInput.Symbols.Select(a => a.Name).Join(",")));
var symbols = Parse(filteredInput.Symbols, content);
return symbols;
}
public class WebRequest
{
private static readonly Logger logger = LogManager.GetCurrentClassLogger();
public virtual async Task<string> GetData(string uri, CancellationToken token)
{
string result = string.Empty;
using (var client = new HttpClient())
using (var response = await client.GetAsync(uri, token).ConfigureAwait(false))
{
if (response.IsSuccessStatusCode)
result = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
else
logger.Error("Unable to retrieve data from the following url: {0} - StatusCode: {1}", uri, response.StatusCode);
}
return result;
}
}
目标是加快 10 个 Web 请求中 1 个的下载速度,以便尽快处理数据并更新 UI,而不是在有限带宽的情况下同时下载 10 个 Web 请求,并且必须在几秒钟后更新 UI .