Skip to content

Commit

Permalink
#12 Add support for async methods
Browse files Browse the repository at this point in the history
  • Loading branch information
Miista committed May 2, 2024
1 parent 2504e79 commit eea75ec
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 2 deletions.
8 changes: 8 additions & 0 deletions src/Pose/Helpers/StubHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,14 @@ public static MethodInfo DeVirtualizeMethod(Type thisType, MethodInfo virtualMet
var bindingFlags = BindingFlags.Instance | (virtualMethod.IsPublic ? BindingFlags.Public : BindingFlags.NonPublic);
var types = virtualMethod.GetParameters().Select(p => p.ParameterType).ToArray();

if (thisType.IsNestedPrivate && thisType.GetInterfaces().Any(i => i.Name == "IAsyncStateMachine"))
{
var nestedType = thisType;
var targetMethod = nestedType.GetInterfaceMap(nestedType.GetInterfaces()[0].GetMethod("MoveNext").DeclaringType).TargetMethods[0];

return targetMethod;
}

return thisType.GetMethod(virtualMethod.Name, bindingFlags, null, types, null);
}

Expand Down
1 change: 1 addition & 0 deletions src/Pose/Shim.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ public static Shim Replace<T>(Expression<Func<T>> expression, bool setter = fals

private static Shim ReplaceImpl<T>(Expression<T> expression, bool setter)
{
// TODO: Figure out if method is an async method. Do that by finding the attribute on the method which designates the state machine
var methodBase = ShimHelper.GetMethodFromExpression(expression.Body, setter, out var instance);
return new Shim(methodBase, instance) { _setter = setter };
}
Expand Down
14 changes: 12 additions & 2 deletions src/Sandbox/Program.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,18 @@
// See https://aka.ms/new-console-template for more information

using System;
using System.Threading.Tasks;

namespace Pose.Sandbox
{
public class Program
{
public static async Task<int> GetIntAsync()
{
Console.WriteLine("Here");
return await Task.FromResult(1);
}

public static void Main(string[] args)
{
#if NET48
Expand All @@ -19,11 +26,14 @@ public static void Main(string[] args)
#elif NETCOREAPP2_0
Console.WriteLine("2.0");
var dateTimeShim = Shim.Replace(() => DateTime.Now).With(() => new DateTime(2004, 1, 1));
var asyncShim = Shim.Replace(() => GetIntAsync()).With(() => Task.FromResult(10));
PoseContext.Isolate(
() =>
{
Console.WriteLine(DateTime.Now);
}, dateTimeShim);
var result = GetIntAsync().GetAwaiter().GetResult();
Console.WriteLine($"Result: {result}");
//Console.WriteLine(DateTime.Now);
}, dateTimeShim, asyncShim);
#elif NET6_0
Console.WriteLine("6.0");
var dateTimeShim = Shim.Replace(() => DateTime.Now).With(() => new DateTime(2004, 1, 1));
Expand Down

0 comments on commit eea75ec

Please sign in to comment.