Skip to main content
 首页 » 编程设计

c#之等待委托(delegate)中调用的任务

2024年02月13日11linjiqin

我有一个看起来像这样的 Controller 方法:

[HttpPut, Route("cqs/command")] 
public HttpResponseMessage Command([ValueProvider(typeof(HeaderValueProviderFactory))] string typeName) 
{ 
    object reply = null; 
    var code = HttpStatusCode.OK; 
    try 
    { 
        var cmdObject = DeserializeRequest(typeName); 
        var method = _commandMethod.MakeGenericMethod(type); 
        method.Invoke(this, new object[] { request }); 
    } 
    catch (Exception exception) 
    { 
        code = HttpStatusCode.InternalServerError; 
        reply = exception; 
    } 
 
    var responseMsg = new HttpResponseMessage(code); 
    if (reply != null) 
    { 
        responseMsg.Headers.Add("X-TypeName", reply.GetType().AssemblyQualifiedName); 
        var replyJson = JsonConvert.SerializeObject(reply); 
        responseMsg.Content = new StringContent(replyJson, Encoding.UTF8, "application/json"); 
    } 
    return responseMsg; 
} 

调用以下方法:

private void ExecuteCommand<T>(T command) where T : Command 
{ 
    var task = _commandBus.ExecuteAsync(command); 
    task.Wait(TimeSpan.FromSeconds(10)); 
} 

原因是 _commandBus 只有一个我需要调用的通用方法。

问题是 ExecuteCommand 有时似乎会死锁。我不知道为什么。 ICommandBus.ExecuteAsync 方法将使用 async/await 调用其他任务,因此它可能是某种死锁,因为 WebApi 使用同步上下文? ( await vs Task.Wait - Deadlock? )

所以如果我理解正确,可能有两种解决方案:

  1. 一直使用 async/await。但是,在使用 MethodInfo 调用方法时我该怎么做呢?
  2. 更改以便我的调用与同步上下文一起工作

当涉及到这两种解决方案时,我迷路了。谁能帮忙?

请您参考如下方法:

更改 ExecuteCommand<T>所以它看起来像这样(我假设您的实际代码会在超时时做一些事情):

private async Task ExecuteCommandAsync<T>(T command) where T : Command 
{ 
  var timeout = Task.Delay(TimeSpan.FromSeconds(10)); 
  var task = _commandBus.ExecuteAsync(command); 
  await Task.WhenAny(task, timeout); 
} 

随便叫它async Task以及。然后,当您调用该方法时,您可以这样做:

var task = method.Invoke(this, new object[] { request }) as Task; 
await task;