1- using Cyaim . WebSocketServer . Infrastructure . Attributes ;
1+ using Cyaim . WebSocketServer . Infrastructure . Attributes ;
22using Cyaim . WebSocketServer . Infrastructure . Configures ;
33using Microsoft . Extensions . Configuration ;
44using Microsoft . Extensions . DependencyInjection ;
1010using System . Collections . Generic ;
1111using System . Globalization ;
1212using System . Linq ;
13+ using System . Linq . Expressions ;
1314using System . Reflection ;
15+ using System . Threading . Tasks ;
1416
1517namespace Cyaim . WebSocketServer . Infrastructure
1618{
@@ -182,6 +184,20 @@ public static void ConfigureWebSocketRoute(this IServiceCollection services, ICo
182184
183185 #endregion
184186
187+ #region 计算终结点返回值Task<TResult>结果读取器缓存
188+
189+ var methodTaskResultGetters = new Dictionary < MethodInfo , Func < Task , object > > ( ) ;
190+ foreach ( var item in points . Select ( x => x . MethodInfo ) )
191+ {
192+ if ( TryBuildTaskResultGetter ( item . ReturnType , out var taskResultGetter ) )
193+ {
194+ methodTaskResultGetters [ item ] = taskResultGetter ;
195+ }
196+ }
197+ wsrOptions . WatchAssemblyContext . MethodTaskResultGetters = methodTaskResultGetters ;
198+
199+ #endregion
200+
185201 services . AddSingleton ( x => wsrOptions ) ;
186202
187203 //services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
@@ -194,6 +210,41 @@ public static void ConfigureWebSocketRoute(this IServiceCollection services, ICo
194210 var defaultCultureInfo = CultureInfo . CurrentCulture ;
195211 }
196212
213+ /// <summary>
214+ /// 编译表达式树以获取 Task<TResult> 的结果,避免每次通过反射访问 Result 属性的性能开销。
215+ /// </summary>
216+ /// <param name="returnType"></param>
217+ /// <param name="getter"></param>
218+ /// <returns></returns>
219+ private static bool TryBuildTaskResultGetter ( Type returnType , out Func < Task , object > getter )
220+ {
221+ getter = null ;
222+ if ( returnType == null || ! returnType . IsGenericType )
223+ {
224+ return false ;
225+ }
226+
227+ var genericTypeDef = returnType . GetGenericTypeDefinition ( ) ;
228+ if ( genericTypeDef != typeof ( Task < > ) )
229+ {
230+ return false ;
231+ }
232+
233+ var resultType = returnType . GenericTypeArguments [ 0 ] ;
234+ if ( resultType . Name == "VoidTaskResult" && resultType . Namespace == "System.Threading.Tasks" )
235+ {
236+ return false ;
237+ }
238+
239+ var taskParam = Expression . Parameter ( typeof ( Task ) , "task" ) ;
240+ var castTask = Expression . Convert ( taskParam , returnType ) ;
241+ var resultProperty = Expression . Property ( castTask , "Result" ) ;
242+ var castResult = Expression . Convert ( resultProperty , typeof ( object ) ) ;
243+
244+ getter = Expression . Lambda < Func < Task , object > > ( castResult , taskParam ) . Compile ( ) ;
245+ return true ;
246+ }
247+
197248 /// <summary>
198249 /// Get assembly controller "WebSocket" EndPoint
199250 /// </summary>
0 commit comments