I have .net 4.0 application does a heavy database search. I want these operations to be asynchronous and also it should be cancellable. Async and await works fine in .net 4.5 which also has executereaderasync methods for Async db operations. But i cannot upgrade to .net 4.5. Task based programming can be used but asynchronizing the db search is priority. Can someone suggest posdible options of achieving this in .net 4.0
2 Answers
You can use async targeting pack (Microsoft.Bcl.Async) to get async-await to work on .NET 4.0. This is a relevant blog on msdn. The targeting pack allows you to use await in Visual Studio 2012 (and newer versions) when targeting any of the following platforms (or higher versions):
- .NET Framework 4.0 (with KB2468871)
- Silverlight 4
- Windows Phone 7.5
- and portable class libraries targeting those platforms.
This way once you can move your application to .NET 4.5 it will be an easy transition as well.
1 Comment
You can grit your teeth and use the Asynchronous Programming Model (APM) that all those async learning materials speak of as a thing of the past. ADO.NET (at least the SQL Server provider) had support for it since .NET 2.0. Specifically, you want the BeginExecute/EndExecute and Cancel methods on the SqlCommand.
4 Comments
async keyword, you can use the above answer to get support for the keyword itself in .NET 4.0, and then use the TaskFactory.FromAsync method family to get an awaitable Task from the pair of the BeginExecute/EndExecute methods. You'd still have to cancel the old way, though.async methods in .NET 4.5 methods use FromAsync under the hood - you can check with the reference source. The implementation of the asynchronous call is thus the same.