背景
我有一些代码使用来自一个特定主机的内容执行批处理 HTML 页面处理。它尝试使用HttpClient
. 我相信同时连接的最大数量受 限制ServicePointManager.DefaultConnectionLimit
,所以我没有应用我自己的并发限制。
将所有请求异步发送到HttpClient
usingTask.WhenAll
后,可以使用CancellationTokenSource
and取消整个批处理操作CancellationToken
。通过用户界面可以查看操作的进度,并且可以单击按钮来执行取消。
问题
调用CancellationTokenSource.Cancel()
阻塞大约 5 - 30 秒。这会导致用户界面冻结。怀疑发生这种情况是因为该方法正在调用注册取消通知的代码。
我所考虑的
- 限制并发 HTTP 请求任务的数量。我认为这是一种解决方法,因为
HttpClient
似乎已经将多余的请求本身排队。 CancellationTokenSource.Cancel()
在非 UI 线程中执行方法调用。这效果不太好。直到大多数其他任务完成后,该任务才真正运行。我认为async
该方法的一个版本会很好用,但我找不到。另外,我觉得它适合在 UI 线程中使用该方法。
示范
代码
class Program
{
private const int desiredNumberOfConnections = 418;
static void Main(string[] args)
{
ManyHttpRequestsTest().Wait();
Console.WriteLine("Finished.");
Console.ReadKey();
}
private static async Task ManyHttpRequestsTest()
{
using (var client = new HttpClient())
using (var cancellationTokenSource = new CancellationTokenSource())
{
var requestsCompleted = 0;
using (var allRequestsStarted = new CountdownEvent(desiredNumberOfConnections))
{
Action reportRequestStarted = () => allRequestsStarted.Signal();
Action reportRequestCompleted = () => Interlocked.Increment(ref requestsCompleted);
Func<int, Task> getHttpResponse = index => GetHttpResponse(client, cancellationTokenSource.Token, reportRequestStarted, reportRequestCompleted);
var httpRequestTasks = Enumerable.Range(0, desiredNumberOfConnections).Select(getHttpResponse);
Console.WriteLine("HTTP requests batch being initiated");
var httpRequestsTask = Task.WhenAll(httpRequestTasks);
Console.WriteLine("Starting {0} requests (simultaneous connection limit of {1})", desiredNumberOfConnections, ServicePointManager.DefaultConnectionLimit);
allRequestsStarted.Wait();
Cancel(cancellationTokenSource);
await WaitForRequestsToFinish(httpRequestsTask);
}
Console.WriteLine("{0} HTTP requests were completed", requestsCompleted);
}
}
private static void Cancel(CancellationTokenSource cancellationTokenSource)
{
Console.Write("Cancelling...");
var stopwatch = Stopwatch.StartNew();
cancellationTokenSource.Cancel();
stopwatch.Stop();
Console.WriteLine("took {0} seconds", stopwatch.Elapsed.TotalSeconds);
}
private static async Task WaitForRequestsToFinish(Task httpRequestsTask)
{
Console.WriteLine("Waiting for HTTP requests to finish");
try
{
await httpRequestsTask;
}
catch (OperationCanceledException)
{
Console.WriteLine("HTTP requests were cancelled");
}
}
private static async Task GetHttpResponse(HttpClient client, CancellationToken cancellationToken, Action reportStarted, Action reportFinished)
{
var getResponse = client.GetAsync("http://www.google.com", cancellationToken);
reportStarted();
using (var response = await getResponse)
response.EnsureSuccessStatusCode();
reportFinished();
}
}
输出
为什么取消阻止这么长时间?另外,有什么我做错了或者可以做得更好吗?