1

Consider following async MVC controller method (There are ~100.000 Customers in database):

public async Task<IEnumerable<Customer>> GetCustomerss()
{
    var query = dbContext.Set<Customer>();
    Debug.WriteLine("Getting customers");
    var task = query.ToListAsync();
    Debug.WriteLine("After getting customers task");
    var taskRes = await task;
    Debug.WriteLine("After awaiting customers");

    var query2 = dbContext.Set<Customer>();
    Debug.WriteLine("Getting customers 2");
    var task2 = query2.ToListAsync();
    Debug.WriteLine("After getting customers task 2");
    var taskRes2 = await task2;
    Debug.WriteLine("After awaiting customers 2");

    return taskRes2;
}

The problem is that in both blocks (query and query2) thread hangs in line with ToListAsync() for about 10 seconds and after that (when printing "After getting customers task..." the task status is RanToCompletion. It seems that the await happens not where await keyword is.

I am aware that EF6 context is not thread safe, this is just an example code. The db is SQL Server 2014 hosted on Azure. ToListAsync() is extension method from System.Data.Entity;

UPDATE: It seems that I missed one important thing - the app uses MiniProfiler and it's probable source of a the problem as suggested in: How to make Entity Framework execute asynchronously

Community
  • 1
  • 1
  • any reason why you don't await ToListAsync(); directly? – Sebi Dec 21 '16 at 08:31
  • If i'd like to read something from file asynchronously after ToListAsync and combine the data from file with customers from dB it would be good for performance. – John Bollock Dec 21 '16 at 08:49
  • Possible duplicate of [EF6 ToListAsync does not run async but blocks the thread](http://stackoverflow.com/questions/31287942/ef6-tolistasync-does-not-run-async-but-blocks-the-thread) – vtortola Dec 21 '16 at 10:55
  • This is not duplicate because mentioned issue solution suggested that behavior was only on first call to EF. Thats why i added duplicate block (query2) in my example – John Bollock Dec 21 '16 at 11:42
  • @JohnBollock: Please show how this is called. – Stephen Cleary Dec 21 '16 at 15:51
  • @StephenCleary - It's inside mvc controller so i'm not calling it directly. I tested this call with dummy awaitable method containing "await Task.Delay(5000)" and awaiting worked properly - thread was not blocked – John Bollock Dec 22 '16 at 08:27

0 Answers0