From d0d938b92adb32b55487cdb046f5c4fb7a69d38c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BC=98=E9=9F=AC=20=E5=BC=A0?= Date: Thu, 7 Jan 2021 11:04:07 +0800 Subject: [PATCH] Add Cancellationtoken for Http.cs --- Flow.Launcher.Infrastructure/Http/Http.cs | 25 ++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/Flow.Launcher.Infrastructure/Http/Http.cs b/Flow.Launcher.Infrastructure/Http/Http.cs index 8e2832690..173be8422 100644 --- a/Flow.Launcher.Infrastructure/Http/Http.cs +++ b/Flow.Launcher.Infrastructure/Http/Http.cs @@ -8,6 +8,7 @@ using Flow.Launcher.Infrastructure.Logger; using Flow.Launcher.Infrastructure.UserSettings; using System; using System.ComponentModel; +using System.Threading; namespace Flow.Launcher.Infrastructure.Http { @@ -94,17 +95,25 @@ namespace Flow.Launcher.Infrastructure.Http /// When supposing the result is long and large, try using GetStreamAsync to avoid reading as string /// /// - /// - public static Task GetAsync([NotNull] string url) + /// The Http result as string. Null if cancellation requested + public static Task GetAsync([NotNull] string url, CancellationToken token = default) { Log.Debug($"|Http.Get|Url <{url}>"); - return GetAsync(new Uri(url.Replace("#", "%23"))); + return GetAsync(new Uri(url.Replace("#", "%23")), token); } - public static async Task GetAsync([NotNull] Uri url) + /// + /// + /// + /// + /// + /// The Http result as string. Null if cancellation requested + public static async Task GetAsync([NotNull] Uri url, CancellationToken token = default) { Log.Debug($"|Http.Get|Url <{url}>"); - using var response = await client.GetAsync(url); + using var response = await client.GetAsync(url, token); + if (token.IsCancellationRequested) + return null; var content = await response.Content.ReadAsStringAsync(); if (response.StatusCode == HttpStatusCode.OK) { @@ -122,10 +131,12 @@ namespace Flow.Launcher.Infrastructure.Http /// /// /// - public static async Task GetStreamAsync([NotNull] string url) + public static async Task GetStreamAsync([NotNull] string url, CancellationToken token = default) { Log.Debug($"|Http.Get|Url <{url}>"); - var response = await client.GetAsync(url); + var response = await client.GetAsync(url, token); + if (token.IsCancellationRequested) + return Stream.Null; return await response.Content.ReadAsStreamAsync(); } }