【问题标题】:in the second call to Post method getting "An asynchronous module or handler completed while an asynchronous operation was still pending"在对 Post 方法的第二次调用中获得“异步模块或处理程序已完成,而异步操作仍处于挂起状态”
【发布时间】:2020-08-07 06:57:25
【问题描述】:

我的 ApiController 中有以下方法,

public  Task<HttpResponseMessage> Post([FromBody] CardParameters paras)
{
        int amount = Convert.ToInt32(paras.Amount);
        int cashout = Convert.ToInt32(paras.CashOut);

        var promise = new TaskCompletionSource<HttpResponseMessage>();

        void getResponse(string s)
        {   
            promise.SetResult(Request.CreateResponse(s)); // this line executes in 2 seconds
        }

        AdpResponse ar =  getResponse;
        ta.purchase(amount, cashout, ar);
        return promise.Task;
}

“ta.purchase” 方法在第三方应用中。该应用程序将在进程结束时调用 "getResponse" 方法。

客户端应用程序在第一次调用此方法时收到结果。 但从第二次调用开始,客户端收到错误 "[InvalidOperationException: 异步模块或处理程序已完成,而异步操作仍处于挂起状态。]

【问题讨论】:

  • 您能分享一下您是如何构建ta 对象的吗?如果可能的话,描述purchase 方法的行为或它的作用也会很有帮助。
  • @DanielCrha 购买方法在 dll 中。当此应用程序调用 purchase 方法时,它会立即返回。不知何故,几秒钟后,结果通过getResponse 方法(委托)发送到这个应用程序。我观察到getResponse 在执行return promise.Task 行后收到结果。

标签: c# asp.net asp.net-web-api task


【解决方案1】:

我通过用一个任务包装整个过程来解决这个问题。 This 文章帮助我理解了这个概念。

setResult(s) 完成了任务,但它没有从 ASP.net 注销任务。因此 ASP.net 在尝试退出该方法时会引发错误。所以我不得不使用任务。这行得通。

public  Task<HttpResponseMessage> Post([FromBody] CardParameters paras){
    int amount = Convert.ToInt32(paras.Amount);
    int cashout = Convert.ToInt32(paras.CashOut);

    string myResult ="";

    var _t = Task.Run(async () =>
    {
         
        var promise = new TaskCompletionSource<HttpResponseMessage>();

        void getResponse(string s)
        {   
            promise.SetResult(s); 
        }

        AdpResponse ar =  getResponse;
        ta.purchase(amount, cashout, ar);
        myResult = promise.Task.Result;
    });
    await _t;
    return Request.CreateResponse(myResult); 
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-30
    • 2013-03-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多