使用异步.NET 4.0返回DataTable [英] Return DataTable using async .net 4.0
问题描述
我有一个返回数据表的方法.我认为使用.net 4.0可以使逻辑异步并返回数据.但是此代码返回空的Datatable对象.任何想法这段代码有什么问题.
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];
}
推荐答案
首先,您不能在.NET 4或C#4中使用async
/await
.这是C#5中的一项新功能.它安装在.NET 4之上,但是这些CTP中确实存在一些错误-不要使用它们.您应该使用.NET 4.5的完整发行版,其中包括C#5编译器. (所有这些都在Visual Studio 2012中.)
Firstly, you can't use async
/ await
with .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.)
其次,如Cuong Le所示,您使用了错误的任务属性. Result
属性是您获得Task<T>
.
Secondly, you're using the wrong property of the task, as Cuong Le showed. The Result
property is how you get at the result of a Task<T>
.
第三,在更改为使用Result
属性后,您将无法获取该表-使其毫无意义.这个:
Thirdly, after making the change to use the Result
property, you'd be blocking for the table to be fetched - making it pointless. This:
public DataTable GetData(string sql, string connectionName)
{
DataTable dt = (DataTable)GetDataAsync(sql, connectionName).Result;
return dt;
}
...在很大程度上等同于:
... is largely equivalent to:
public DataTable GetData(string sql, string connectionName)
{
return FillData(sql, connectionName);
}
如果您要开始执行任务并立即等待,您最好同步地调用该方法.
If you're going to start a task and immediately wait on it, you might as well just call the method synchronously.
这篇关于使用异步.NET 4.0返回DataTable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!