0

I've been learning how to use asynchronous calls with Entity Framework recently and have been experimenting with the behaviors of the various calls. However, I've come up against a problem and I'm not sure what's causing it.

So in my data access class, I have an async method like this:

public static async Task update(int id)
{
    var task1 = doSomething(id);
    var task2 = doSomethingElse(id);
    await Task.WhenAll(task1, task2);    
}

It calls on the two async tasks which are in the following form:

private static async Task doSomething(int id)
{
    using (var context = new dbEntity())
    {
        //...make changes to the context
        await context.SaveChangesAsync();
    }
}

private static async Task doSomethingElse(int id)
{
    using (var context = new dbEntity())
    {
        //...make changes to the context
        await context.SaveChangesAsync();
    }
}

Finally, in the controller, I'm calling on the data access async task like this:

public ActionResult Index(int id)
{
    var task = DataAccess.update(id);
    task.Wait();
    return View();
}

When I go and trigger the Index action, my application just hangs indefinitely. What's strange is that when I stop the application and look at my database, it appears that both of the async SaveChanges went through and the data in my database has been modified. When I remove the call to task.Wait(), the application proceeds as normal. I think I'm causing a deadlock somewhere, but I don't know where. Can some please point me in the right direction and tell me what exactly is happening here?

Thanks!

1

2 Answers 2

2

You can not mix async code with synchronous code. When you use task.wait() you are blocking the thread.

Please change the controller action to the following:

public async Task<ActionResult> Index(int id)
{
    await DataAccess.update(id);
    return View();
}
Sign up to request clarification or add additional context in comments.

Comments

1

I am eager to hear why it's stalling, but you should nevertheless change your Index method to asynchronous to complete the pipe...

public async Task<ActionResult> Index(int id)
{
    await DataAccess.update(id);
    return View();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.