I have a method that returns a datatable. I thought using .net 4.0 I could just async logic and return data. But this code returns null Datatable object. Any ideas what is wrong with this code.
public DataTable GetData(string sql, string connectionName)
{
DataTable dt = (DataTable)GetDataAsync(sql, connectionName).AsyncState;
return dt;
}
private async Task<DataTable> GetDataAsync(string sql, string connectionName)
{
return await TaskEx.Run(() => { return FillData(sql, connectionName); });
}
private DataTable FillData(string sql, string connectionName)
{
SqlConnection conn = _connections.Where(w => w.ConnectionName == connectionName).Single().Connection;
SqlDataAdapter adp = new SqlDataAdapter(sql, conn);
DataSet ds = new DataSet();
adp.Fill(ds);
return ds.Tables[0];
}
Firstly, you can’t use
async/awaitwith .NET 4 or C# 4. It’s a new feature in C# 5. There were CTPs which installed on top of .NET 4, but there are definite bugs in those CTPs – don’t use them. You should use the full release version of .NET 4.5, which includes the C# 5 compiler. (All this is in Visual Studio 2012.)Secondly, you’re using the wrong property of the task, as Cuong Le showed. The
Resultproperty is how you get at the result of aTask<T>.Thirdly, after making the change to use the
Resultproperty, you’d be blocking for the table to be fetched – making it pointless. This:… is largely equivalent to:
If you’re going to start a task and immediately wait on it, you might as well just call the method synchronously.