异步填充数据表? [英] Fill DataTable asynchronously?

查看:32
本文介绍了异步填充数据表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 .NET Core 2.0 应用中有以下功能.

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 SqlDataAdapter(sql, connStr);
    da.Fill(dt);
    return dt;
}

如何将其转换为异步函数?

How to convert it to an async function?

public async Task<DataTable> CallDb(string connStr, string sql)
{
    var dt = new DataTable();
    var da = new SqlDataAdapter(sql, connStr);
    da.Fill(dt); // No FillAsync to await?
    return dt;
}

我需要使用 DataTable 因为 sql 可能返回具有不同架构的数据.有没有更好的方法来处理动态架构?

I need to use DataTable because the sql may return data with different schema. Any better way to handle the dynamical schema?

推荐答案

虽然在这种情况下对 ExecuteReaderAsync() 的初始调用不会阻塞,dt.Load(reader)code> 可能相当于 reader.Read() 而不是 await reader.ReadAsync(),并且可能在检索行时阻塞调用线程.

Although the initial call to ExecuteReaderAsync() will not block in this case, dt.Load(reader) probably does the equivalent of reader.Read() rather than await reader.ReadAsync(), and may block the calling thread while retrieving rows.

如果您确实需要一个 DataTable 与外部 API 一起使用,或者因为您事先不知道字段定义,但需要完全异步行为,则最好使用您的自己的代码来构造一个DataTable,添加所需的列,例如基于 reader.GetName()reader.GetFieldType(),然后使用 await reader.ReadAsync()dt.Rows.Add().

If you do need a DataTable for use with an external API, or because you don't know the field definitions in advance, but require fully asynchronous behaviour, you might be better off to use your own code to construct a DataTable, add the required columns e.g. based on reader.GetName() and reader.GetFieldType(), and then populate it with rows in a loop using await reader.ReadAsync() and dt.Rows.Add().

这篇关于异步填充数据表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆