开发者

How can I execute different methods at the same time?

开发者 https://www.devze.com 2023-02-06 21:40 出处:网络
In my application I am using a dataset and 4 methods like below. 开发者_运维技巧 Dataset ds=new Dataset();

In my application I am using a dataset and 4 methods like below.

开发者_运维技巧
Dataset ds=new Dataset();
ds=businesslogiclayerObject.method1(a,b,c,d);
ds=businesslogiclayerObject.method2(a,b,c,d,e);
ds=businesslogiclayerObject.method3(a,b,c,d,e,f);
ds=businesslogiclayerObject.method4(a,b,c,d,e,f,g,h);

(a,b,c,d,e,f,g,h) are the parameters to Stored Procedure in Businesslogic Layer. Till now I did not implement any threading concept so they are executing one by one.This takes lot of time to get result set in Dataset.

How can I execute above 4 methods at the same time?

Help me.

Regards, N.SRIRAM


Since you are using .NET 3 you could make use the BackgroundWorker as this will take care of the marshaling effort back to your UI thread as well as some of the other complexities of threading. It will not however take care of locking; so be sure to address the locking aspect if needed.

BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += new DoWorkEventHandler(OnGrabData);
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(OnGrabDataCompleted);
worker.RunWorkerAsync(new DataClass(a,b,c,d,e,f,g));

DataClass could encapsulate your parameters which your stored procedure will then access or perhaps you could pass a delegate with the parameters which can then be called within the BackgroundWorker. Either way the BackgroundWorker should suffice in this example to provide simplistic threading behavior.


if your "businesslayer" executes some sort of sql and returns a dataset you could rewrite that to execute all sql-statements with one batch; seperate each individual sql/sproc call with ;

the result-dataset will have a datatable for each seperate sql.


First of all, there are few things to think about:

  1. The methods will never actually execute at the same time
  2. The total execution time will probably be bigger than when executed sequentially.
  3. You should evaluate if the order of execution is relevant.

If that's not a problem (for instance if you just want to process the calls in the background), then there are several options. The easiest is probably using the threadpool, using ThreadPool.QueueUserWorkItem(), or using a BackgroundWorker.

Depending on your exact needs, you could capture the required parameters in a list or dictionary, or define a seperate state object, and do something like:

Dictionary<string, object> parameters = new Dictionary<string, object>
parameters.Add("a", 42); 
parameters.Add("b", new object());
parameters.Add("c", null);
ThreadPool.QueueUserWorkItem((state) => { do stuff with "state" }, parameters);.
0

精彩评论

暂无评论...
验证码 换一张
取 消