异步填充DataTable? [英] Fill DataTable asynchronously?

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

问题描述

我在.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)可能等效于 reader.Read()而不是等待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(),然后使用循环在行中填充它等待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().

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

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