From c3c5b41b30118a247a996c8fb0b46e576b3c8366 Mon Sep 17 00:00:00 2001 From: Brenton Farmer Date: Wed, 28 Aug 2024 16:49:19 -0700 Subject: [PATCH] Eliminate DynamicInvoke --- .../AsyncExpression.cs | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/src/Hyperbee.AsyncExpressions/AsyncExpression.cs b/src/Hyperbee.AsyncExpressions/AsyncExpression.cs index f5f9267..bf1ce22 100644 --- a/src/Hyperbee.AsyncExpressions/AsyncExpression.cs +++ b/src/Hyperbee.AsyncExpressions/AsyncExpression.cs @@ -105,14 +105,14 @@ public bool TryProcessCallableNode( Expression node, IReadOnlyCollection) _visitedParameters : arguments; var argArray = NewArrayInit( typeof(object), ConvertArguments( argItems ) ); //return ExecuteAsyncExpression(node.Type.GetGenericArguments()[0], _body, VisitedParameters.ToArray(), arguments); - result = Call( executeMethod!, [Constant( _body ), Constant( _visitedParameters.ToArray() ), argArray] ); + result = Call( executeAsyncMethod!, [Constant( _body ), Constant( _visitedParameters.ToArray() ), argArray] ); return true; } @@ -213,10 +213,19 @@ public void MoveNext() { // Initial state: compile the expression and execute it + //var delegateType = GetDelegateType( _parameterExpressions.Select( p => p.Type ).Concat( [typeof(Task)] ).ToArray() ); + //var lambda = Lambda( delegateType, _body, _parameterExpressions ); + //var compiledLambda = lambda.Compile(); + //var task = compiledLambda.DynamicInvoke( _parameters ); + var delegateType = GetDelegateType( _parameterExpressions.Select( p => p.Type ).Concat( [typeof(Task)] ).ToArray() ); - var lambda = Lambda( delegateType, _body, _parameterExpressions ); - var compiledLambda = lambda.Compile(); - var task = compiledLambda.DynamicInvoke( _parameters ); + var bodyLambda = Lambda( delegateType, _body, _parameterExpressions ); + + var parameterExpressions = _parameters.Select( Constant ).Cast().ToArray(); + var invocationExpression = Invoke( bodyLambda, parameterExpressions ); + + var invocationLambda = Lambda>>( invocationExpression ).Compile(); + var task = invocationLambda(); awaiter = ((Task) task!).ConfigureAwait( false ).GetAwaiter();