Jak*_*lås 3 .net c# dotnet-httpclient
我试图在命令行应用程序中取消通过共享HttpClient使用完整框架、.net 4.7.1、C# 7.3、VS 2017 发出的多个异步 Web 请求 (GET)。CancellationTokens
我的示例运行几个并行任务,每个任务都使用异步不断通过 Http 下载一些数据,GetAsync()但ReadAsStringAsync()使用 example 得到相同的结果ReadAsByteArrayAsync()。
终止是通过挂接Console.CancelKeyPress并取消我的CancellationTokenSource.
尽管由于某种原因这看起来很简单,但我无法理解它并想出一个产生可靠结果的解决方案。有时,一切都会按预期关闭,即所有任务都完成(取消),但更常见的是,不关闭只是看似挂起。在不使用调试器(带/不带 DEBUG)的情况下运行会终止应用程序,但不会以我预期的方式终止。任务越少意味着干净关闭的可能性越大。
当处于“挂起”状态时暂停调试中的所有线程似乎表明某些线程被卡住GetAsync(),但很难准确地看到发生了什么。
实际上,应用程序如何退出并不重要,但我想了解这一点,并能够一致地产生干净且受控的关闭,对我来说,使用这种构造似乎是可能的,但我很可能错过了一些细节。
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace HttpClientAsyncTest
{
class Program
{
static async Task<int> Main()
{
using (var cancellationTokenSource = new CancellationTokenSource())
{
Console.CancelKeyPress += (sender, a) =>
{
Console.WriteLine("Stopped by user");
cancellationTokenSource.Cancel();
};
var task = RunAsync(cancellationTokenSource);
Console.WriteLine("Running - Press CTRL+C to stop");
await task;
}
Console.WriteLine("All done, exiting");
return 0;
}
private static async Task RunAsync(CancellationTokenSource cts)
{
using (var client = new HttpClient())
{
try
{
var tasks = Enumerable.Range(1, 10).Select(id => ProcessBatchAsync(client, id, cts.Token));
await Task.WhenAll(tasks);
}
catch (OperationCanceledException)
{
Console.WriteLine("Operation cancelled somehow");
}
}
}
private static async Task ProcessBatchAsync(HttpClient client, int id, CancellationToken cancellationToken)
{
while (true)
await ProcessNextBatchAsync(client, id, cancellationToken);
}
private static async Task ProcessNextBatchAsync(HttpClient client, int id, CancellationToken cancellationToken)
{
using (var response = await client.GetAsync("http://some.payload.to.request", cancellationToken))
{
if (response.StatusCode == HttpStatusCode.NotFound)
return;
var data = await response.Content.ReadAsStringAsync();
Console.WriteLine($"Id: {id} downloaded {data.Length} chars");
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我希望在按 Ctrl-C 时看到类似的内容:
Running - Press CTRL+C to stop
Id: 6 downloaded 475357 chars
Id: 2 downloaded 475141 chars
Id: 3 downloaded 474927 chars
Id: 5 downloaded 474457 chars
Id: 8 downloaded 474524 chars
Id: 4 downloaded 474643 chars
Id: 7 downloaded 475133 chars
Id: 9 downloaded 475316 chars
Stopped by user
Operation cancelled somehow
All done, exiting
Press any key to continue . . .
Run Code Online (Sandbox Code Playgroud)
但大多数情况下我得到的都是这样的:
Running - Press CTRL+C to stop
Id: 3 downloaded 474927 chars
Id: 8 downloaded 474524 chars
Id: 5 downloaded 474457 chars
Id: 9 downloaded 475316 chars
Id: 6 downloaded 475357 chars
Id: 7 downloaded 474952 chars
Id: 2 downloaded 475513 chars
Stopped by user
Id: 4 downloaded 475457 chars
Id: 7 downloaded 475133 chars
^CPress any key to continue . . .
Run Code Online (Sandbox Code Playgroud)
好吧,我通过 StackOverflow 的橡皮鸭再次成功了。
Ctrl+C如果没有通过 取消,则终止应用程序,因此它与或 的args.Cancel = true关系绝对为零。HttpClientCancellationToken
修复方法很简单:
Console.CancelKeyPress += (sender, args) =>
{
args.Cancel = true;
Console.WriteLine("Stopped by user");
cancellationTokenSource.Cancel(true);
};
Run Code Online (Sandbox Code Playgroud)