Multi-async in Entity Framework 6?

An Hv picture An Hv · Dec 17, 2013 · Viewed 40.4k times · Source

This is my code:

var banner = context.Banners.ToListAsync()
var newsGroup = context.NewsGroups.ToListAsync()
await Task.WhenAll(banner, newsGroup);

But when i called the function from controller. It showed error

A second operation started on this context before a previous asynchronous operation completed. Use 'await' to ensure that any asynchronous operations have completed before calling another method on this context. Any instance members are not guaranteed to be thread safe.

Please help me solve this issue.

Answer

Stephen Cleary picture Stephen Cleary · Dec 17, 2013

The exception explains clearly that there is only one asynchronous operation per context allowed at a time.

So, you either have to await them one at a time as the error message suggests:

var banner = await context.Banners.ToListAsync();
var newsGroup = await context.NewsGroups.ToListAsync();

Or you can use multiple contexts:

var banner = context1.Banners.ToListAsync();
var newsGroup = context2.NewsGroups.ToListAsync();
await Task.WhenAll(banner, newsGroup);