Using Linq to Sql asynchronously with the new async / wait

What are the best practices for using L2S ​​with the new C # 5 async/await keywords compared to this ? Could not be found on the Internet.

+6
source share
2 answers

EF 5 does not support async / await support, but the open source version is actively exploring the possibilities here. EDIT: Async support in EF is documented at http://msdn.microsoft.com/en-us/data/jj819165.aspx . It does not pass the results because they are hydrated (as you would find with RX), but it makes an asynchronous database.

As for LINQ to SQL, outside of packing your query in the Task.Factory.Start operation, I would not hold my breath hoping that the async task (required for async / await) would be implemented by Microsoft for Linq for SQL.

You can use IQToolkit and extend it by adding your own async support if absolutely necessary. In addition, Mono has implemented LINQ to SQL, which you can expand with async support.

+6
source
Scott Hanselman has an interesting post where he demonstrates how to create an asynchronization API on top of an existing Linq to SQL query. I don’t have time to think too much about this idea, but I suppose that you can create a more general extension method that would allow any object of type IQueryable or IEnumerable to deploy the same method.

Here is the code directly from his post to use as a link.

 SqlCommand _beginFindCmd = null; public IAsyncResult BeginFind(int id, AsyncCallback callback, Object asyncState) { var query = from w in _db.Widgets where w.Id == id select w; _beginFindCmd = _db.GetCommand(query) as SqlCommand; _db.Connection.Open(); return _beginFindCmd.BeginExecuteReader(callback, asyncState, System.Data.CommandBehavior.CloseConnection); } public Widget EndFind(IAsyncResult result) { var rdr = _beginFindCmd.EndExecuteReader(result); var widget = (from w in _db.Translate<Widget>(rdr) select w).SingleOrDefault(); rdr.Close(); return widget; } 

With a bit of work, this TPL could be made as well as even cleaner as a single asynchronous method. If I have a chance to do this, I will post what I came up with.

+3
source

Source: https://habr.com/ru/post/925781/


All Articles