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

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

问题描述

使用C#/ .NET 3.5。

Using C# / .NET 3.5.

目前我正在使用SqlDataAdapter.Fill()填充2个DataTable。

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

我想并行地填充这两个DataTable,同时通过异步执行每个数据表。但是,没有异步版本的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 //第二个查询,for DataTable2

  3. SqlCommand1.EndExecuteReader

  4. SqlCommand2.EndExecuteReader

  5. DataTable1.Load(DataReader1)

  6. DataTable2.Load(DataReader2)

  1. SqlCommand1.BeginExecuteReader // 1st query, for DataTable1
  2. SqlCommand2.BeginExecuteReader // 2nd query, for DataTable2
  3. SqlCommand1.EndExecuteReader
  4. SqlCommand2.EndExecuteReader
  5. DataTable1.Load(DataReader1)
  6. DataTable2.Load(DataReader2)

但是,DataTable.Load()需要很长时间: />
需要3秒钟才能执行步骤1到步骤4。

步骤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.Fill,一个接一个。我想要的结果是,整个过程只需要最长的查询(或尽可能接近)。

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? / p>

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