SqlDataAdapter.Fill - 异步方法 [英] SqlDataAdapter.Fill - Asynchronous approach

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

问题描述

使用 C#/.NET 3.5.

Using C# / .NET 3.5.

目前我正在使用 SqlDataAdapter.Fill() 一个接一个地填充 2 个数据表.

Currently I'm populating 2 DataTables one after the other using SqlDataAdapter.Fill().

我想并行填充这两个数据表,同时通过异步执行每个数据表.但是,Fill() 方法没有异步版本 - 即 BeginFill() 会很棒!

I want to populate both of these DataTables in parallel, at the same time by doing each one asynchronously. However, there is no asynchronous version of the Fill() method - i.e. BeginFill() would be great!

我尝试过的一种方法是(伪):

One approach I've tried is (pseudo):

  1. SqlCommand1.BeginExecuteReader//第一个查询,用于 DataTable1
  2. SqlCommand2.BeginExecuteReader//第二个查询,用于 DataTable2
  3. SqlCommand1.EndExecuteReader
  4. SqlCommand2.EndExecuteReader
  5. DataTable1.Load(DataReader1)
  6. DataTable2.Load(DataReader2)

但是,DataTable.Load() 需要很长时间:
第1步到第4步需要3秒.
第 5 步需要 22 秒.
第 6 步需要 17 秒.
因此,第 5 步和第 6 步合并为 39 秒.

However, DataTable.Load() takes a long time:
It takes 3 seconds to do step 1 to step 4.
Step 5 then takes 22 seconds.
Step 6 takes 17 seconds.
So, combined 39 seconds for steps 5 and 6.

最终结果是,这比我一个接一个地执行 2 个 SqlDataAdapter.Fills 没有任何好处.我希望最终结果是整个过程只需要与最长查询一样长(或尽可能接近).

The end result is, this gives me no benefit over just doing 2 SqlDataAdapter.Fills, one after the other. I want the net result to be that the entire process takes only as long as the longest query (or as close to that as possible).

寻找推荐的方法,最终得到一种真正的异步方法来填充数据表.

Looking for recommended ways forward to end up with something that is truly an asynchronous approach to filling a DataTable.

还是我自己管理它并滚动 2 个单独的线程,每个线程填充一个 DataTable?

Or do I just manage it myself and roll 2 separate threads, each one filling a DataTable?

推荐答案

我建议每个都有一个单独的工作线程.您可以使用 ThreadPool.QueueUserWorkItem.>

I would suggest have a separate worker thread for each. You could use ThreadPool.QueueUserWorkItem.

List<AutoResetEvent> events = new List<AutoResetEvent>();

AutoResetEvent loadTable1 = new AutoResetEvent(false);
events.Add(loadTable1);
ThreadPool.QueueUserWorkItem(delegate 
{ 
     SqlCommand1.BeginExecuteReader;
     SqlCommand1.EndExecuteReader;
     DataTable1.Load(DataReader1);
     loadTable1.Set();
});

AutoResetEvent loadTable2 = new AutoResetEvent(false);
events.Add(loadTable2);
ThreadPool.QueueUserWorkItem(delegate 
{ 
     SqlCommand2.BeginExecuteReader;
     SqlCommand2.EndExecuteReader;
     DataTable2.Load(DataReader2);
     loadTable2.Set();
});

// wait until both tables have loaded.
WaitHandle.WaitAll(events.ToArray());

这篇关于SqlDataAdapter.Fill - 异步方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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