1

As we know Ms Sql 2000 does not support MultipleActiveResultSets.

Can i use Dapper with async Task without exceptions :

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

My code example

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());
}

}

Thank you.

ondemand
  • 13
  • 4
  • I'm guessing you're still sharing the same SQL connection? have you tried spawning different connections? [How do I handle Database Connections with Dapper in .NET?](http://stackoverflow.com/questions/9218847/how-do-i-handle-database-connections-with-dapper-in-net) – Balah Jan 14 '16 at 14:46
  • Thank you @Balah for the information. I will try. – ondemand Mar 11 '16 at 10:09

1 Answers1

0

It looks like your code should work, although I'm very confused as to why you're using Task.Factory.StartNew everywhere; you shouldn't have to do that, and indeed: it is not ideal to do so.

I also can't see how / where SqlConn is defined, so for all I know it is indeed being accessed concurrently. However, to rewrite your code more idiomatically:

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());
    }
}

Notice: no Task.Factory.StartNew; it uses the async implementation of the backing service.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900