Fill DataTable asynchronously?

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<DataTable> 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.

Leave a Comment