Asynchronous Processing in EF6 and .NET 4.5
Courtesy Peter Vogel, VisualStudioMagazine.com
There’s one feature of Entity Framework (EF) 6 that’s only available in the Microsoft .NET Framework 4.5 or later: asynchronous processing. In this column, I’m going to look at some typical scenarios where you can use EF asynchronous processing and show how you might use it.
First Scenario: Processing Multiple Requests in Parallel
Often, when you first display a form or a page, you need to display some initial set of data and also fill some combo boxes or dropdown lists. With asynchronous processing you can issue the request for the grid’s data and, while waiting for that data to show up, go on to issue the requests for the combo box data, overlapping the requests. Even if the database server processes your requests sequentially, you’re no worse off than if you submitted the requests in sequence. But, if the database server does process your requests in parallel, your users might get their data considerably earlier. Best of all, this is a scenario that doesn’t add much complexity to your application. This could be your first big win in asynchronous processing.
But … EF doesn’t support processing multiple requests through the same DbContext object. If your second asynchronous request on the same DbContext instance starts before the first request finishes (and that’s the whole point), you’ll get an error message that your request is processing against an open DataReader. I’ll look at some ways to handle this issue after looking at how to issue overlapping asynchronous requests.
A little pre-retrieval work is required. First, you’ll need an Imports or using statement for System.Data.Entity to pick up the asynchronous extension methods that EF6 supplies. You should also disable the controls you’re filling so the user can’t interact with them while you’re loading data.