请问大家,在使用多个backgroundworker的时候,如果通过传参(bgw.RunWorkerAsync(type);)来区分执行DoWork方法里面的哪一段代码的话,这样子会有问题吗?还是一个backgroundworker对应自己的一个DoWork方法好呢?如果用同一个的话,我怕多个线程启动时,传进的参数e.Argument会被覆盖(我不清楚它们是否占用的是同一块地址),请大家给下意见,谢谢
例如是:
#region 国内排名
private void bgwChinaSort_DoWork(object sender, DoWorkEventArgs e)
{
}
#endregion
#region 谷歌PR,搜狗SR
private void bgwPRSR_DoWork(object sender, DoWorkEventArgs e)
{
}
#endregion
还是只有一个DoWork方法,然后获取传入参数type来判断了
private void bgw_DoWork(object sender, DoWorkEventArgs e)
{
if(e.Argument.Tostring()= "XXX")
{
}
else
{
}
}
我怕第二种方法当多个线程同时启动时,e.Argument会出现被覆盖的情况,希望大家能给点意见
不会的。
对线程来说只是代码段而已,参数不会被覆盖,独立运行的
没太明白,backgroundworker把线程封装的太多了,封装多的坏处就是个性化的东西不好实现,如果楼主实在搞不定,就自己写下线程,估计可以解决问题
不知道是不是这样的,如果是的话,貌似不影响的:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using MultiThread.WaitHandleDemo; using MultiThread.ThreadPoolDemo; using System.ComponentModel;
namespace MultiThread { public class Prograss { static Random random = new Random(); static void Main() { //EventWaitHandleDemo ewhd = new EventWaitHandleDemo(); //Console.WriteLine("Result = {0}.", // ewhd.Result(234).ToString()); //Console.WriteLine("Result = {0}.", // ewhd.Result(55).ToString()); BackgroundWorker bWorker = new BackgroundWorker(); bWorker.DoWork += MyWork; bWorker.RunWorkerAsync(Num.one); BackgroundWorker bWorker1 = new BackgroundWorker(); bWorker1.DoWork += MyWork; bWorker1.RunWorkerAsync(Num.two); BackgroundWorker bWorker2 = new BackgroundWorker(); bWorker2.DoWork += MyWork; bWorker2.RunWorkerAsync(Num.zero); BackgroundWorker bWorker3 = new BackgroundWorker(); bWorker3.DoWork += MyWork; bWorker3.RunWorkerAsync(); //RegistWaitForSignalDemo demo = new RegistWaitForSignalDemo(); //demo.OutPutThreadPoolInfo(); //demo.InitDemo(); Console.ReadLine(); }
private static void MyWork(object sender, DoWorkEventArgs e) { string temp = "null"; if(e.Argument != null)temp = e.Argument.ToString(); Thread.Sleep(random.Next(100, 1000)); if (temp == Num.one.ToString()) { Console.WriteLine("param is one"); } else if (temp == Num.two.ToString()) { Console.WriteLine("param is two"); } else if (temp == Num.zero.ToString()) { Console.WriteLine("param is zero"); } else { Console.WriteLine("no params found"); } Console.WriteLine("xxxxxxxxxxxxxxxxxxxxxx"); } }
public enum Num { zero, one, two } }