如何异步使用DataAdapter.Fill()? [英] How to use DataAdapter.Fill() asynchronously?

查看:274
本文介绍了如何异步使用DataAdapter.Fill()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个DataAdapter可以填充一个DataSet中的5个数据表。

I have a DataAdapter that is filling 5 DataTables in a DataSet.

SqlDataAdapter da = new SqlDataAdapter("Select * from testTable",con);
da.Fill(ds, 0, numberOfRowsToPutInEachDataTable, "DT1");
da.Fill(ds, numberOfRowsToPutInEachDataTable , numberOfRowsToPutInEachDataTable , "DT2");
da.Fill(ds, numberOfRowsToPutInEachDataTable* 2, numberOfRowsToPutInEachDataTable, "DT3");
da.Fill(ds, numberOfRowsToPutInEachDataTable * 3, numberOfRowsToPutInEachDataTable, "DT4");
da.Fill(ds, numberOfRowsToPutInEachDataTable * 4, numberOfRowsToPutInEachDataTable, "DT5");

我的目标是获得每个

da.Fill...

可以在

我没有异步运行事物的经验,并且很难通过研究找到解决方案。谁能告诉我如何使每个DataAdapter.Fill()异步运行?

I have no experience running things asynchronously and am having a hard time finding the solution through research. Can anyone show me how I can get each of these DataAdapter.Fill() to run asynchronously?

推荐答案

您可以使用多个线程这样的多个 Task.Run()

You can use multiple threads of multiple Task.Run() this way:

Task.Run(() =>
{
    da1.Fill(ds.Table1);
    this.Invoke(new Action(() => {dataGridView1.DataSource = ds.Table1;}));
});
Task.Run(() =>
{
    da2.Fill(ds.Table2);
    this.Invoke(new Action(() => {dataGridView2.DataSource = ds.Table2;}));
});

这样,数据将同时使用2个不同的线程加载而不会冻结表单。

This way data will load using 2 different threads at the same time without freezing the form.

在上面的代码中, da1.Fill da2.Fill 同时调用不同的线程。由于代码执行的线程不同于UI线程,因此要设置 DataGridView DataSource ,应使用调用

In above code, da1.Fill and da2.Fill will call in different threads at the same time. Since the code is executing a different thread than UI thread, to set the DataSource of DataGridView you should use Invoke.

这篇关于如何异步使用DataAdapter.Fill()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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