将数据异步加载到 Windows 窗体中的 DataTable 中 [英] Load data asynchronously into DataTable in Windows Forms

查看:33
本文介绍了将数据异步加载到 Windows 窗体中的 DataTable 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在修改旧的 WinForms/ADO 应用程序的数据访问层,以通过异步 developerforce rest api 使用 soql 获取 Salesforce 对象.以下方法通常有效,除了我的 13 个表例程之一永远不会从 AddMyTableRow (System.Data.DataRowCollection.Add()) 方法返回:

I'm modifying the data access layer of an old WinForms/ADO app to get Salesforce objects using soql over the asynchronous developerforce rest api. The following approach generally works, except that one of my thirteen tables routines never returns from the AddMyTableRow (System.Data.DataRowCollection.Add()) method:

public void LoadData() {
    var tasks = new List<Task<int>> {
        GetObject1Async(),
        GetObject2Async(),...
        GetObject13Async()
    };
    Task.WaitAll(tasks.ToArray());
    //do some postprocessing now that I have all the data
}

async Task<int> GetObject1Async(){
    var response = await cnx.QueryAsync<dynamic>("SELECT foo FROM bar").ConfigureAwait(false);
    foreach (var rec in response.Records){
        var row = MyDataSet.MyTable.NewMyTableRow();
        row.Name = rec.Name; ...
        MyDataSet.MyTable.AddMyTableRow(row); //<== Sometimes this never returns
    }
    return MyDataSet.MyTable.Count;
}

这是否是正确的方法?

我发现,如果我注释掉整个 await cnx.Query... 行并调用 AddMyTableRow(dummyData) 就可以了.我觉得有某种异步/线程/上下文正在发生,但由于它没有产生任何类型的错误或异常,我不知道该怎么办.

I've found that if I comment out the whole await cnx.Query... line and just call AddMyTableRow(dummyData) it works. I feel like there is some kind of async /threading / context something going on, but since its not generating any kind of error or exception I don't know what to go on.

干杯,杰夫

推荐答案

您可以拥有一个 async 方法,它返回 Task 然后异步表单 Load 事件处理程序或在要执行数据绑定的异步方法中,等待调用它,然后使用结果绑定到网格.

You can have an async method which returns Task<DataTable> and then in async form Load event handler or in the async method which you want to perform data-binding, await call it, then use the result to bind to the grid.

示例

public async Task<DataTable> GetDataAsync(string command, string connection)
{
    var dt = new DataTable();
    using (var da = new SqlDataAdapter(command, connection))
        await Task.Run(() => da.Fill(dt));
    return dt;
}

private async void Form1_Load(object sender, EventArgs e)
{
    var command = @"SELECT * FROM Category";
    var connection = @"Your Connection String";
    var data = await GetDataAsync(command, connection);
    this.dataGridView1.DataSource = data;
}

要了解如何在 DataGridView 上显示加载动画,请查看这篇文章.

To see how you can show a loading animation over the DataGridView, take a look at this post.

这篇关于将数据异步加载到 Windows 窗体中的 DataTable 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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