Fill DataTable asynchronously?

后端 未结 2 693
没有蜡笔的小新
没有蜡笔的小新 2020-12-11 04:48

I have the following function in a .NET Core 2.0 app.

public DataTable CallDb(string connStr, string sql)
{
    var dt = new DataTable();
    var da = new Sq         


        
2条回答
  •  生来不讨喜
    2020-12-11 05:21

    SqlDataAdapter was never updated to include the TPL version of the methods. You could do this:

    await Task.Run(() => da.Fill(dt));
    

    But that would be creating a thread that would do nothing useful.

    A good approach would be to use something like this:

    public async Task CallDb(string connStr, string sql)
    {
        var dt = new DataTable();
        var connection = new SqlConnection(connStr);
        var reader = await connection.CreateCommand().ExecuteReaderAsync();
        dt.Load(reader);
    
        return dt;
    }
    

    Of course, some changes like using statements should be made. However, here you are using asynchronous calls the right way.

提交回复
热议问题