How to make an asynchronous action method call in MVC4

I have the following scenario. How to perform parallel processing when a database call is executed asynchronously.

/// <summary>
    /// Async query EF6.0
    /// </summary>
    /// <returns></returns>
    public async Task<ActionResult> AsyncQuery()
    {
        var result = await GetAsyncDepartments();
        Debug.WriteLine("Do some stuff here");

        return View("Index");
    }

    private async Task<List<Department>> GetAsyncDepartments()
    {
        var depts = new List<Department>();
        using (var newContext = new DemoEntities())
        {
            depts = await newContext.Departments.ToListAsync();
        }
        Debug.WriteLine("Got departments");
        return depts;
    }

He actually waits for the task to complete, and then proceeds to the statement, "Do something here."

How can I call GetAsyncDepartments () asynchronously and do some extra things until the call returns. Thank.

+4
source share
2 answers

GetAsyncDepartmentswill return an instance Taskthat you can "wait" after "some state" has been executed.

public async Task<ActionResult> AsyncQuery()
{
    var task = GetAsyncDepartments();
    Debug.WriteLine("Do some stuff here");

    await task;
    return View("Index");
}
+2
source

await . GetAsyncDepartments, await , . :

async Task Main()
{
    var finalResult = await AsyncQuery();
    Console.WriteLine(finalResult);
}

public async Task<int> AsyncQuery()
{
    var result = GetAsyncDepartments();
    Debug.WriteLine("Do some stuff here");
    return await result;
}

public async Task<int> GetAsyncDepartments()
{
    Console.WriteLine("Starting GetAsyncDepartments");
    await Task.Delay(5000);
    Console.WriteLine("Finished GetAsyncDepartments");
    return 5;
}

:

GetAsyncDepartments
-
GetAsyncDepartments
5

+2

Source: https://habr.com/ru/post/1663390/


All Articles