Introduction
Microsoft .NET 4.5 introduced new "async and await" methods to provide an easy way of implementing asynchronisity using .NET "Task" objects.
This allows developers to make async calls more flexibly, as opposed to standard threading/callback methods.
In this article i've built a demo to show how this can be applied to build easy to use SQL functions which can be called async.
Getting started
For this article we shall be using the .NET SQL Client library for connecting to a Microsoft SQL Server database, however the same methodology of wrapping up code in a task can be used with any other type of connection.
In this example we will wrap our code which connects to the database to get data into a function which returns a "Task" object based on the data type we require.
Building Asynchronous Task Functions
We start by building the initial wrapper which returns a task object. We shall be returning a dataset in this example.
Side note: Any data type can be returned with task objects, as such you could return a string, integer or a custom class.
The following is the basic wrapper for our function. This bit of code will return a task object based on the datatype, with a section to add our own code to build and return the dataset.
public Task GetDataSetAsync(string sConnectionString, string sSQL)
{
return Task.Factory.StartNew(() =>
{
//MY CODE HERE
});
}
We can now insert code which connects to the server to get data based on a query into this function.
Example 1: Function to fill a dataset based on the SQL query.
In this example code has been added to the body of the function which uses a standard SQL connection strin