/
aprogrammer
/
dotnet-docs
Обзор
Документация
Войти
/
aprogrammer
/
dotnet-docs
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
main
docs/csharp/asynchronous-programming/snippets/cancel-tasks/Program.cs
96 строк
3 KB
Bill Wagner
Xamarin to maui (#40538)
25 апр 2024, 18:27
Не верифицирован
25 апр 2024, 18:27
38ec336
Код
Авторство
О чём код?
using System.Diagnostics; class Program { static readonly CancellationTokenSource s_cts = new CancellationTokenSource(); static readonly HttpClient s_client = new HttpClient { MaxResponseContentBufferSize = 1_000_000 }; static readonly IEnumerable<string> s_urlList = new string[] { "https://learn.microsoft.com", "https://learn.microsoft.com/aspnet/core", "https://learn.microsoft.com/azure", "https://learn.microsoft.com/azure/devops", "https://learn.microsoft.com/dotnet", "https://learn.microsoft.com/dynamics365", "https://learn.microsoft.com/education", "https://learn.microsoft.com/enterprise-mobility-security", "https://learn.microsoft.com/gaming", "https://learn.microsoft.com/graph", "https://learn.microsoft.com/microsoft-365", "https://learn.microsoft.com/office", "https://learn.microsoft.com/powershell", "https://learn.microsoft.com/sql", "https://learn.microsoft.com/surface", "https://learn.microsoft.com/system-center", "https://learn.microsoft.com/visualstudio", "https://learn.microsoft.com/windows", "https://learn.microsoft.com/maui" }; static async Task Main() { Console.WriteLine("Application started."); Console.WriteLine("Press the ENTER key to cancel...\n"); Task cancelTask = Task.Run(() => { while (Console.ReadKey().Key != ConsoleKey.Enter) { Console.WriteLine("Press the ENTER key to cancel..."); } Console.WriteLine("\nENTER key pressed: cancelling downloads.\n"); s_cts.Cancel(); }); Task sumPageSizesTask = SumPageSizesAsync(); Task finishedTask = await Task.WhenAny(new[] { cancelTask, sumPageSizesTask }); if (finishedTask == cancelTask) { // wait for the cancellation to take place: try { await sumPageSizesTask; Console.WriteLine("Download task completed before cancel request was processed."); } catch (OperationCanceledException) { Console.WriteLine("Download task has been cancelled."); } } Console.WriteLine("Application ending."); } static async Task SumPageSizesAsync() { var stopwatch = Stopwatch.StartNew(); int total = 0; foreach (string url in s_urlList) { int contentLength = await ProcessUrlAsync(url, s_client, s_cts.Token); total += contentLength; } stopwatch.Stop(); Console.WriteLine($"\nTotal bytes returned: {total:#,#}"); Console.WriteLine($"Elapsed time: {stopwatch.Elapsed}\n"); } static async Task<int> ProcessUrlAsync(string url, HttpClient client, CancellationToken token) { HttpResponseMessage response = await client.GetAsync(url, token); byte[] content = await response.Content.ReadAsByteArrayAsync(token); Console.WriteLine($"{url,-60} {content.Length,10:#,#}"); return content.Length; } }