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

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

问题描述

使用C#/。NET 3.5。

Using C# / .NET 3.5.

目前我正在填充2数据表一前一后使用SqlDataAdapter.Fill()。

Currently I'm populating 2 DataTables one after the other using SqlDataAdapter.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 //月1日查询,为DataTable1
  2. SqlCommand2.BeginExecuteReader //第二查询,为DataTable2
  3. SqlCommand1.EndExecuteReader
  4. SqlCommand2.EndExecuteReader
  5. DataTable1.Load(DataReader1)
  6. DataTable2.Load(DataReader2)

不过,DataTable.Load()需要很长的时间:
需要3秒做步骤1到步骤4。
第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).

寻找推荐的前进道路,以最终的东西是真正的异步方式来填充一个DataTable。

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天全站免登陆