Entity Framework with Asynchronous behaviours


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:

await context.SavesChangesAsync();

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

  where e.Name.StartsWith("V")

  select e;

 

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.

Advertisements

2 thoughts on “Entity Framework with Asynchronous behaviours

  1. Sebastian

    ForEachAsync does not force the execution to stream the data. You need to add .AsStreaming() to the query before. Then it works like a charm even with large amounts of data.

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s