From 35eacdf329974d4821a9149ee5d9c4c54d0ac8e5 Mon Sep 17 00:00:00 2001 From: David Eriksson Date: Mon, 25 Nov 2024 20:20:02 +0100 Subject: [PATCH] TaskConverter generation 3 Solves #37 --- .../Helpers/Implementation/TaskConverter3.cs | 35 +++++++++++++++++++ .../Implementation/TaskConverter3Factory.cs | 12 +++++++ Activout.RestClient/Services.cs | 2 +- 3 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 Activout.RestClient/Helpers/Implementation/TaskConverter3.cs create mode 100644 Activout.RestClient/Helpers/Implementation/TaskConverter3Factory.cs diff --git a/Activout.RestClient/Helpers/Implementation/TaskConverter3.cs b/Activout.RestClient/Helpers/Implementation/TaskConverter3.cs new file mode 100644 index 0000000..7e98bf6 --- /dev/null +++ b/Activout.RestClient/Helpers/Implementation/TaskConverter3.cs @@ -0,0 +1,35 @@ +using System; +using System.Diagnostics; +using System.Threading.Tasks; + +namespace Activout.RestClient.Helpers.Implementation; + +/* + * Convert from Task to Task where T is the Type + * + * Implemented by creating a TaskCompletionSource and setting the result or exception + */ +public class TaskConverter3 : ITaskConverter +{ + [StackTraceHidden] + public object ConvertReturnType(Task task) + { + return ConvertReturnTypeImpl(task); + } + + [StackTraceHidden] + private static async Task ConvertReturnTypeImpl(Task task) + { + var taskCompletionSource = new TaskCompletionSource(); + try + { + taskCompletionSource.SetResult((T)await task); + } + catch (Exception e) + { + taskCompletionSource.SetException(e); + } + + return await taskCompletionSource.Task; + } +} \ No newline at end of file diff --git a/Activout.RestClient/Helpers/Implementation/TaskConverter3Factory.cs b/Activout.RestClient/Helpers/Implementation/TaskConverter3Factory.cs new file mode 100644 index 0000000..a0af67b --- /dev/null +++ b/Activout.RestClient/Helpers/Implementation/TaskConverter3Factory.cs @@ -0,0 +1,12 @@ +using System; + +namespace Activout.RestClient.Helpers.Implementation; + +public class TaskConverter3Factory : ITaskConverterFactory +{ + public ITaskConverter CreateTaskConverter(Type actualReturnType) + { + return actualReturnType == typeof(void) ? null : + (ITaskConverter) Activator.CreateInstance(typeof(TaskConverter3<>).MakeGenericType(actualReturnType)); + } +} \ No newline at end of file diff --git a/Activout.RestClient/Services.cs b/Activout.RestClient/Services.cs index 3b81ff2..06cd9e1 100644 --- a/Activout.RestClient/Services.cs +++ b/Activout.RestClient/Services.cs @@ -15,7 +15,7 @@ public static IDuckTyping CreateDuckTyping() public static ITaskConverterFactory CreateTaskConverterFactory() { - return new TaskConverter2Factory(); + return new TaskConverter3Factory(); } public static IRestClientFactory CreateRestClientFactory(