2012年12月13日

Entity Framework 6では非同期DB処理がこんなに簡単に書ける!

MicrosoftのScott Guthrie氏のブログで Entity Framework 6 の Alpha 2 がダウンロード可能になったと報告されている。

Entity Framework 6: Alpha2 Now Available - ScottGu's Blog

改善点としてまっさきに挙げられているのは「非同期処理のサポート」。

.NET 4.5 introduced the Task-Based Asynchronous Pattern that uses the async and await keywords to help make writing asynchronous code easier. EF 6 now supports this pattern. This is great for ASP.NET applications as database calls made through EF can now be processed asynchronously – avoiding any blocking of worker threads. This can increase scalability on the server by allowing more requests to be processed while waiting for the database to respond.
The following code shows an MVC controller that is querying a database for a list of location entities:

(以下意訳)

.NET 4.5ではTaskベースの非同期実行のパターンが追加されました。このパターンでは async と await キーワードを使って非同期に実行されるコードを容易に記述する事が出来ます。EF6 も今回このパターンをサポートしました。
EF経由のデータベース呼び出しを非同期で実行する事が可能になるので、これはASP.NETアプリケーションにとっては非常に望ましい事です。 - つまりワーカスレッドをブロックせずともよくなるのです。これによってデータベースからの応答を待つ間に他のリクエストを処理出来るので、サーバー側でのスケーラビリティの向上に寄与します。
次のコードはLocationエンティティの一覧をデータベースから取得するMVCコントローラの例です。


    public class HomeController : Controller
    {
        LocationContext db = new LocationContext();

        public async Task<ActionResult> Index()
        {
            var locations = await db.Locations.ToListAsync();

            return View(locations);
        }
    }
上のコードを見ると、青字の部分が変わっただけで、他は今までと同じ。とても読みやすい。これだけでコントローラ側が非同期処理になるとは、素晴らしいの一言。

最近は Node.js がかなり注目されているけれども、その理由の一つが「非同期処理によるスケーラビリティの向上」にある。Entity Framework 6で非同期なDB処理がここまで簡潔に書ける様になると、ASP.NETもその方向にまた一歩近づいたという事になると思う。