【问题标题】:DataGrid empty when loaded from async SqlDataReader从异步 SqlDataReader 加载时 DataGrid 为空
【发布时间】:2020-08-03 15:22:41
【问题描述】:

我从 SqlDataReader 加载 DataTable,然后将它数据绑定到数据网格。当我同步执行阅读器时,数据网格会正确加载。当我异步执行阅读器时,数据网格为空。这是代码。

同步 - 工作

        async public Task<DataTable> GetDataTableAsync()
    {
        DataTable result = new DataTable();
        await this.Conn.OpenAsync();
        SqlDataReader reader = this.Comm.ExecuteReader();
        result.Load(reader);
        this.Conn.Close();
        return result;
    }

异步 ​​- 不起作用

        async public Task<DataTable> GetDataTableAsync()
    {
        DataTable result = new DataTable();
        await this.Conn.OpenAsync();
        SqlDataReader reader = await this.Comm.ExecuteReaderAsync();
        result.Load(reader);
        this.Conn.Close();
        return result;
    }

DataTable 在这两种情况下完全一样。

项目是经典的 ASP.NET,数据网格是 Telerik RadGrid

【问题讨论】:

  • 什么是“this.Comm”?
  • this.Comm 是带有 sql 文本和参数的 SqlCommand 实例

标签: asp.net asynchronous data-binding datatable


【解决方案1】:

所以我的答案是解释~为什么你的代码不起作用。我添加了一个 SOF 来帮助您找到工作代码。

我认为内部......

    result.Load(reader);

不调用 .ExecuteReaderAsync

所以你是手动调用

SqlDataReader reader = await this.Comm.ExecuteReaderAsync();

(真的什么都不做)

然后 .Load 也不用它做任何事情。

我认为你必须追赶

(查看此答案)

Populate C# DataTable Asynchronously

【讨论】:

  • 断点,我看到读者确实得到了记录。但是在 result.Load(reader); 之后它们不会被加载到 DataTable 中
  • 可以看源码。 referencesource.microsoft.com/#system.data/system/Data/… 我怀疑(正如我之前提到的).... .Load(reader) 不调用/使用 ExecuteReaderAsync
  • 实际上,我发现数据库在这两种情况下都被正确填满。数据绑定不起作用,我为此编辑了问题。
猜你喜欢
  • 2020-10-22
  • 2018-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-03
  • 2022-11-16
相关资源
最近更新 更多