Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use DataAdapter.Fill() asynchronously?

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");

My goal is to get each

da.Fill...

to run asynchronously, at the same time.

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?

like image 787
Reeggiie Avatar asked Oct 29 '22 23:10

Reeggiie


1 Answers

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;}));
});

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

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.

like image 146
Reza Aghaei Avatar answered Nov 15 '22 05:11

Reza Aghaei