Net 4.0 与 Dapper 和 Ms Sql 2000

Net 4.0 with Dapper and Ms Sql 2000

我们知道 Sql 女士 2000 不支持 MultipleActiveResultSets。

我可以毫无例外地将 Dapper 与异步任务一起使用吗:

"There is already an open DataReader associated with this Command which must be closed first."

我的代码示例

private async void Form_Load(object sender, EventArgs e){
var sql1 = "select * from Tab1";
var sql2 = "select * from Tab2";
var sql3 = "select * from Tab3";

await Task.Factory.StartNew(() => FillComboBoxWithData(this.cbo1, sql1));
await Task.Factory.StartNew(() => FillComboBoxWithData(this.cbo2, sql2));
await Task.Factory.StartNew(() => FillComboBoxWithData(this.cbo3, sql3));

}

public static async Task FillComboBoxWithData(ComboBox comboBox, string sql{
try
{

    var data = await Task.Factory.StartNew(() => SqlConn.Query<IdName>(sql));
    var d1 = data.ToNonNullList();

    comboBox.DataSource = d1;

    comboBox.DisplayMember = "Name";
    comboBox.ValueMember = "Id";
    comboBox.SelectedItem = null;
}
catch (Exception ex)
{
    Console.Write(ex.ToString());
}

}

谢谢。

看起来你的代码应该可以工作,虽然我很困惑为什么你到处都使用 Task.Factory.StartNew;你不应该这样做,事实上:这样做并不理想。

我也看不到 SqlConn 是如何/在哪里定义的,所以就我所知它确实被同时访问了。但是,要更地道地重写您的代码:

private async void Form_Load(object sender, EventArgs e)
{
    await FillComboBoxWithData(this.cbo1, "select from Tab1");
    await FillComboBoxWithData(this.cbo2, "select from Tab2");
    await FillComboBoxWithData(this.cbo3, "select from Tab3");
}

public static async Task FillComboBoxWithData(ComboBox comboBox, string sql)
{
    try
    {
        var data = (await SqlConn.QueryAsync<IdName>(sql)).AsList();

        comboBox.DataSource = data;
        comboBox.DisplayMember = "Name";
        comboBox.ValueMember = "Id";
        comboBox.SelectedItem = null;
    }
    catch (Exception ex)
    {
        Console.Write(ex.ToString());
    }
}

注意:没有Task.Factory.StartNew;它使用支持服务的异步实现。