2

I've got a situation where I need to have a single LINQ query run non-asynchronously. Reason: There is currently still a bug in how async EF calls load large blobs (more info on that Entity Framework async operation takes ten times as long to complete)

So my options to fix the above bug are to either convert the query to a custom DbCommand and run raw SQL asynchronously, OR I can just change the call from ToListAsync to a ToList.

TLDR --- Question: I know that calling asynchronous code synchronously can cause a deadlock (e.g. query.ToListAsync().Result), however, does calling the non-asynchronous version of ToList inside of an asynchronous method have the same issue?

EverPresent
  • 1,903
  • 17
  • 21
  • List will hold every object inside it , a large List will consume large memory. I recomend you IQueryable are typically streaming and they are consumed like IEnumerable and they don’t need to hold all the elements they return in memory. To use a ToList inside an async method you have to use Task.Run(() =>) and Task.Wait(); other wise will note complete the task – Pedro Brito Sep 16 '19 at 15:11

2 Answers2

5

I know that calling asynchronous code synchronously can cause a deadlock (e.g. query.ToListAsync().Result), however, does calling the non-asynchronous version of ToList inside of an asynchronous method have the same issue?

Calling a synchronous method like ToList() blocks the current thread regardless of whether you do it inside a method that is meant to be asynchronous. So it won't deadlock but it will block the calling method. And you don't expect an asynchronous to block. Remember that an async method runs synchronously like any other method until it hits an await.

mm8
  • 163,881
  • 10
  • 57
  • 88
3

You can keep the async await signature without compiler warnings if you use

return await Task.FromResult(query.ToList());
Andro Font
  • 356
  • 1
  • 13