Skip to content

Commit

Permalink
TaskConverter generation 3
Browse files Browse the repository at this point in the history
Solves #37
  • Loading branch information
twogood committed Nov 25, 2024
1 parent 0c63404 commit 64dc915
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 1 deletion.
35 changes: 35 additions & 0 deletions Activout.RestClient/Helpers/Implementation/TaskConverter3.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
using System;
using System.Diagnostics;
using System.Threading.Tasks;

namespace Activout.RestClient.Helpers.Implementation;

/*
* Convert from Task<object> to Task<T> where T is the Type
*
* Implemented by creating a TaskCompletionSource<T> and setting the result or exception
*/
public class TaskConverter3<T> : ITaskConverter
{
[StackTraceHidden]
public object ConvertReturnType(Task<object> task)
{
return ConvertReturnTypeImpl(task);
}

[StackTraceHidden]
private static async Task<T> ConvertReturnTypeImpl(Task<object> task)
{
var taskCompletionSource = new TaskCompletionSource<T>();
try
{
taskCompletionSource.SetResult((T)await task);
}
catch (Exception e)
{
taskCompletionSource.SetException(e);
}

return await taskCompletionSource.Task;
}
}
Original file line number Diff line number Diff line change
@@ -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));
}
}
2 changes: 1 addition & 1 deletion Activout.RestClient/Services.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public static IDuckTyping CreateDuckTyping()

public static ITaskConverterFactory CreateTaskConverterFactory()
{
return new TaskConverter2Factory();
return new TaskConverter3Factory();
}

public static IRestClientFactory CreateRestClientFactory(
Expand Down

0 comments on commit 64dc915

Please sign in to comment.