如何将此代码转换为任务并行库.因此,.net仅注意并行运行此任务. [英] How to convert this code to Task Parallel Library. So that .net only take care to run this tasks parallel.

查看:62
本文介绍了如何将此代码转换为任务并行库.因此,.net仅注意并行运行此任务.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是c#.net中多线程编程的新手,

我有一个当前使用4 Background Worker的应用程序.

所以我宣布:

I’m new to multithread programming in c# .net,

I have an application that currently uses 4 Background Worker.

So I declare them:

private BackgroundWorker bw1;
private BackgroundWorker bw2;
private BackgroundWorker bw3;
private BackgroundWorker bw4;


然后配置它们:


Then configure them:

bw1 = new BackgroundWorker();
bw1.WorkerReportsProgress = true;
bw1.DoWork += new DoWorkEventHandler(bw1_DoWork);
bw1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw1_RunWorkerCompleted);
bw1.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);

bw2 = new BackgroundWorker();
bw2.WorkerReportsProgress = true;
bw2.DoWork += new DoWorkEventHandler(bw2_DoWork);
bw2.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw2_RunWorkerCompleted);
bw2.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);

bw3 = new BackgroundWorker();
bw3.WorkerReportsProgress = true;
bw3.DoWork += new DoWorkEventHandler(bw3_DoWork);
bw3.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw3_RunWorkerCompleted);
bw3.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);

bw4 = new BackgroundWorker();
bw4.WorkerReportsProgress = true;
bw4.DoWork += new DoWorkEventHandler(bw4_DoWork);
bw4.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw4_RunWorkerCompleted);
bw4.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);



然后我使用bw1.RunWorkerAsync()bw2.RunWorkerAsync()等...

关键是我永远不会同时调用它们,它们以相当线性的方式在不同点调用.

如何将这段代码转换为任务并行库,以使.net仅注意并行运行此任务?



And then I use the bw1.RunWorkerAsync(), bw2.RunWorkerAsync(), and so on...

The thing is I never call them simultaneously, they are call at different point in a pretty linear way.

How do I convert this code to Task Parallel Library so that .net only take care to run this tasks parallel?

推荐答案

您好,请尝试以下操作:

Hi try this:

Parallel.Invoke(new Action(Method1),new Action(Method2),new Action(Method3),...);


在适当的方法bw_DoWork中,methods1 ... n是您的逻辑.


where methods1...n is your logic in appropriate methods bw_DoWork.


这篇关于如何将此代码转换为任务并行库.因此,.net仅注意并行运行此任务.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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