EverPresent
EverPresent

Reputation: 1970

From an async method, is calling a LINQ query's ToList, instead of ToListAsync, a potential deadlock?

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?

Upvotes: 2

Views: 1395

Answers (2)

Andro Font
Andro Font

Reputation: 356

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

return await Task.FromResult(query.ToList());

Upvotes: 3

mm8
mm8

Reputation: 169360

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.

Upvotes: 5

Related Questions