Async and await in MVC 4 Controller

后端 未结 3 625
梦谈多话
梦谈多话 2020-12-18 19:57

Every time I try to use the new Async and Await operators and return a collection of objects from a database I get an Invalid Operation

相关标签:
3条回答
  • 2020-12-18 20:24

    It's been some time since this question was answered. But I was having a similar situation with MVC 5 and I was able to make a [ChildActionOnly] work asynchronously just by commenting out the following line under <system.web> section of web.config file.

    <system.web>
        <!--<httpRuntime targetFramework="4.5" />-->
    

    EDIT: Consider this a workaround while you find a real solution for your situation. Please see Leri's comments below.

    0 讨论(0)
  • 2020-12-18 20:39

    First of all, you cannot use asynchronous processing with child actions and I suppose this is what you are trying to do.

    Secondly, you are not doing any asynchronous processing here by spinning up another thread to execute your code with the below line of code:

    Task.Run(() => GetAllEnvironments());
    

    It will block a thread at the end of the day and you will have nothing but a context switch overhead. EF6 will have support for asynchronous processing. For asynchronous queries with pure ADO.NET, have a look:

    Asynchronous Database Calls With Task-based Asynchronous Programming Model (TAP) in ASP.NET MVC 4

    0 讨论(0)
  • 2020-12-18 20:44

    It's been a while since this was answered but another way around is as follows:

    Call your method from an action

    @Html.Action("YourSyncMethod", "YourController")
    

    Define it as a normal sync action

    public ActionResult YourSyncMethod()
    

    Then inside it call your async method

    var taskResponse = YourAsyncMethod(); 
    

    which will return a model with whatever you need

    private async Task<YourModel> YourAsyncMethod()
    

    It seems simpler than tampering with config options or creating more complex code

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