如何在MVC4中执行异步调用操作方法

时间:2016-12-10 08:43:48

标签: c# asp.net-mvc-4 asynchronous entity-framework-6 task-parallel-library

我在这里有以下情况。如何在DB调用异步运行时进行一些并行处理。

/// <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;
    }

它实际上等待任务完成,然后转到语句“在这里做一些事情”。

如何异步调用GetAsyncDepartments()并执行一些额外的操作直到调用返回。 谢谢。

2 个答案:

答案 0 :(得分:2)

GetAsyncDepartments将返回Task的实例,您可以&#34;等待&#34;在&#34;一些员工&#34;将被执行。

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

    await task;
    return View("Index");
}

答案 1 :(得分:2)

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