I have this code to retrieve data from my database:
public async Task<IEnumerable<Member>> GetAllMembersAsync()
{
var members = Repository.GetAll<Member>();
return await Task.Run(() => members.ToListAsync());
}
For an unknown reason (maybe a bug?), I have to use Task.Run
in order to make this work (the repository just returns a DbSet<Member>
. If I don't do this, my UI hangs forever.
The problem is that I can't do 2 database operations at the same time this way. If I do this, I get this 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.
As you see, I'm already using await
.
Is there any way to solve this so I can actually do 2 database operations at the same time and so they run in order?
EDIT: Code that calls this:
private async void LoadMembers()
{
try
{
var members = await MemberService.GetAllMembersAsync();
Members = new ObservableCollection<Member>(members);
}
catch (EntityException)
{
// connection lost?
}
}