4

I have the following scenario here. How can make some parallel processing while the DB call runs 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;
    }

It actually waits for the Task to be completed and then goes to the statement "Do some stuff here".

How can call the GetAsyncDepartments() asynchronously and do some extra stuff till the call returns. Thank you.

Srikant Sahu
  • 839
  • 1
  • 6
  • 16

2 Answers2

2

GetAsyncDepartments will return instance of Task which you can "await" after "some staff" will be executed.

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

    await task;
    return View("Index");
}
Fabio
  • 31,528
  • 4
  • 33
  • 72
2

await is asking your code to await the call. You can call GetAsyncDepartments, but only await the result when you need it. For example:

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

Produces the output:

Starting GetAsyncDepartments
Do some stuff here
Finished GetAsyncDepartments
5

Rob
  • 26,989
  • 16
  • 82
  • 98
  • 1
    Thank you for your answer. It is really explanatory. However, I have selected the other answer just because of the minimal changes needed. – Srikant Sahu Dec 10 '16 at 09:13