Calling async method in controller

前端 未结 1 379
说谎
说谎 2020-12-14 08:02

I have a controller with something like the following:

public MyController : Controller
{
    public ActionResult DoSomething()
    {
        CallSomeMethodW         


        
相关标签:
1条回答
  • 2020-12-14 08:17

    Now I dont have control over CallSomeMethodWhichDoesAsyncOperations and the method itself is not async but internally does some async fire and forget. What can I do to fix it?

    Contact the person who wrote it and make them fix it.

    Seriously, that's the best option. There's no good fix for this - only a hack.

    You can hack it to work like this:

    public MyController : Controller
    {
      public async Task<ActionResult> DoSomething()
      {
        await Task.Run(() => CallSomeMethodWhichDoesAsyncOperations());
        return Json(new { success = successful }, JsonRequestBehavior.AllowGet);
      }
    }
    

    This is not recommended. This solution pushes off work to a background thread, so when the async operations resume, they will not have an HttpContext, etc. This solution completes the request while there is still processing to be done. This solution will not behave correctly if the server is stopped/recycled at just the wrong time.

    There is only one proper solution: change CallSomeMethodWhichDoesAsyncOperations.

    0 讨论(0)
提交回复
热议问题