问题
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?
回答1:
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
.
回答2:
How about using PLINQ:
SqlDataAdapter da = new SqlDataAdapter("Select * from testTable", con);
IEnumerable<int> results = new string[]
{
"DT1", "DT2", "DT3", "DT4", "DT5"
}
.AsParallel()
.Select((table, index) => da.Fill(ds,
numberOfRowsToPutInEachDataTable * index,
numberOfRowsToPutInEachDataTable,
table));
EDIT
The proposed solution is definitely not recommended.
It appears that DataSet does not support concurrent write operations:
This type is safe for multithreaded read operations. You must synchronize any write operations.
来源:https://stackoverflow.com/questions/38488393/how-to-use-dataadapter-fill-asynchronously