They finally did it: the future release of Entity Framework (version 6) will sport asynchronous behaviour based on .NET 4.0 Task Parallel Library (TPL).
The API is pretty neat. First the SaveChanges gets an async brother SaveChangesAsync returning a Task. So we can now write things like:
The more complicated topic is the queries. LINQ was designed before TPL and doesn’t have the notion of asynchrony. They got around it in a clever fashion: LINQ describe the queries while EF allows you to enumerate the result in an asynchronous fashion:
var q = from e in context.Employees
await q.ForEachAsync(e => Console.WriteLine(e.FirstName));
So the entire enumeration is done asynchronously hence Entity Framework can manage the moment when it needs to fetch the DB for new objects.
This new feature is quite powerful since DB access is typically a place where your thread blocks, waiting for something external. For instance, a web service doing a query and returning data is typically written synchronously with the thread blocking waiting for the DB server. Using this new asynchronous mode, we can as easily write an asynchronous version, much more scalable since no threads are blocking, hence more thread can be used to process requests.