Skip to content

Commit a78fab8

Browse files
committed
fix: 修复ws获取异步方法结果同步阻塞问题
1 parent f9a848f commit a78fab8

1 file changed

Lines changed: 33 additions & 12 deletions

File tree

Cyaim.WebSocketServer/Cyaim.WebSocketServer/Infrastructure/Handlers/MvcHandler/MvcChannelHandler.cs

Lines changed: 33 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1062,23 +1062,44 @@ public static async Task<MvcResponseScheme> MvcDistributeAsync(WebSocketRouteOpt
10621062
invokeResult = methodInvoker.Invoke(inst, args);
10631063

10641064
// Async api support
1065-
if (invokeResult is Task)
1065+
if (invokeResult is Task task)
10661066
{
1067-
dynamic invokeResultTask = invokeResult;
1068-
//await invokeResultTask;
1069-
await Task.WhenAny(invokeResultTask, Task.Delay(Timeout.Infinite, appLifetime.ApplicationStopping));
1070-
1071-
if (invokeResultTask.Exception != null)
1067+
// 检查是否是 Task<T> 类型
1068+
var taskType = task.GetType();
1069+
if (taskType.IsGenericType && taskType.GetGenericTypeDefinition() == typeof(Task<>))
10721070
{
1073-
throw invokeResultTask.Exception;
1074-
}
1071+
// 这是 Task<T>,需要获取返回值
1072+
// 先 await 任务完成,避免同步阻塞
1073+
await task.ConfigureAwait(false);
10751074

1076-
try
1077-
{
1078-
invokeResult = invokeResultTask.Result;
1075+
// 检查任务是否有异常
1076+
if (task.IsFaulted && task.Exception != null)
1077+
{
1078+
// 抛出内部异常(AggregateException 的第一个内部异常)
1079+
var innerException = task.Exception.InnerException ?? task.Exception;
1080+
throw innerException;
1081+
}
1082+
1083+
// 使用反射获取 Result 属性值(此时任务已完成,不会阻塞)
1084+
var resultProperty = taskType.GetProperty("Result");
1085+
if (resultProperty != null)
1086+
{
1087+
invokeResult = resultProperty.GetValue(task);
1088+
}
10791089
}
1080-
catch (RuntimeBinderException)
1090+
else
10811091
{
1092+
// 这是 Task(无返回值),直接 await
1093+
await task.ConfigureAwait(false);
1094+
1095+
// 检查任务是否有异常
1096+
if (task.IsFaulted && task.Exception != null)
1097+
{
1098+
// 抛出内部异常(AggregateException 的第一个内部异常)
1099+
var innerException = task.Exception.InnerException ?? task.Exception;
1100+
throw innerException;
1101+
}
1102+
10821103
invokeResult = null;
10831104
}
10841105
}

0 commit comments

Comments
 (0)