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

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

问题描述

我正在修改一个旧WinForms / ADO应用程序的数据访问层,以通过soql通过异步developerforce rest api获取Salesforce对象。除了我的十三个表例程之一从未从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;
}

这是正确的方法吗?

我发现,如果我将整个acn cnx.Query ...行注释掉,然后调用AddMyTableRow(dummyData),它将起作用。我感觉好像正在发生某种异步/ threading / context的事情,但是由于它不会产生任何类型的错误或异常,所以我不知道该怎么办。

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.

干杯,
Jeff

Cheers, Jeff

推荐答案

您可以使用 async 方法,该方法返回 Task< DataTable> ,然后以异步形式 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天全站免登陆