From 5d801a71660d70291dfb4bc28de9c7951cf78b85 Mon Sep 17 00:00:00 2001 From: Yoshi Askharoun Date: Sun, 7 May 2023 21:56:04 -0500 Subject: [PATCH] Add hacky async-as-sync helpers --- ZuneImpl/AsyncHelper.cs | 26 ++++++++++++++++++++++++++ ZuneImpl/Extensions.cs | 38 +++++++++++++++++--------------------- 2 files changed, 43 insertions(+), 21 deletions(-) create mode 100644 ZuneImpl/AsyncHelper.cs diff --git a/ZuneImpl/AsyncHelper.cs b/ZuneImpl/AsyncHelper.cs new file mode 100644 index 0000000..80e4786 --- /dev/null +++ b/ZuneImpl/AsyncHelper.cs @@ -0,0 +1,26 @@ +using CommunityToolkit.Diagnostics; +using System; +using System.Threading.Tasks; + +namespace Microsoft.Zune; + +public static class AsyncHelper +{ + public static void Run(Task task) + { + if (task == null) + return; + + var t = Task.Run(() => task); + t.Wait(); + } + + public static TResult Run(Func> action) + { + Guard.IsNotNull(action); + + var t = Task.Run(action); + t.Wait(); + return t.Result; + } +} diff --git a/ZuneImpl/Extensions.cs b/ZuneImpl/Extensions.cs index f68298f..5032fbb 100644 --- a/ZuneImpl/Extensions.cs +++ b/ZuneImpl/Extensions.cs @@ -1,31 +1,27 @@ using System; using System.IO; using System.Threading; - -#if NETSTANDARD1_0_OR_GREATER using System.Net.Http; using System.Threading.Tasks; -#endif -namespace Microsoft.Zune +namespace Microsoft.Zune; + +internal static class Extensions { - internal static class Extensions - { #if NETSTANDARD2_0_OR_GREATER && !NET5_0_OR_GREATER - public static Stream ReadAsStream(this HttpContent content) - { - return Task.Run(content.ReadAsStreamAsync).Result; - } - - public static HttpResponseMessage Send(this HttpClient client, HttpRequestMessage request) - { - return Task.Run(() => client.SendAsync(request)).Result; - } - - public static Task GetStreamAsync(this HttpClient client, Uri uri, CancellationToken _) - { - return client.GetStreamAsync(uri); - } -#endif + public static Stream ReadAsStream(this HttpContent content) + { + return AsyncHelper.Run(content.ReadAsStreamAsync); } + + public static HttpResponseMessage Send(this HttpClient client, HttpRequestMessage request) + { + return AsyncHelper.Run(() => client.SendAsync(request)); + } + + public static Task GetStreamAsync(this HttpClient client, Uri uri, CancellationToken _) + { + return client.GetStreamAsync(uri); + } +#endif }