I'm using the following code to run several threads to process some time-consuming tasks :
public void RunWhileRemainThreads()
{
string[] options = new string[2];
int i = 0;
while (LeftToRun > 0)
{
if (CurrentRunningThreads < MaxThreadsRunning)
{
options[0] = list_test[i];
options[1] = bla;
BackgroundWorker myThread = new BackgroundWorker();
myThread.DoWork += new DoWorkEventHandler(backgroundWorkerRemoteProcess_DoWork);
myThread.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorkerRemoteProcess_RunWorkerCompleted);
myThread.ProgressChanged += new ProgressChangedEventHandler(backgroundWorkerRemoteProcess_ProgressChanged);
myThread.WorkerReportsProgress = true;
myThread.WorkerSupportsCancellation = true;
myThread.RunWorkerAsync(options);
Thread.Sleep(3000);
CurrentRunningThreads++;
i++;
LeftToRun--;
}
}
}
private void backgroundWorkerRemoteProcess_DoWork(object sender, DoWorkEventArgs e)
{
string[] options = (string[])e.Argument;
string option1 = options[0];
string option2 = options[1];
RemoteProcess myRemoteProcess = new RemoteProcess(option1, option2);
myRemoteProcess.FalseExec();
}
My problem is that when I run this without the Thread.Sleep(3000)
, the option1
variable is the same! (I print it from within RemoteProcess.FalseExec()
).
I guess I should manage t开发者_Go百科his parameter differently but I cannot find how.
You simply need to stop sharing the same array between all background workers:
public void RunWhileRemainThreads()
{
int i = 0;
while (LeftToRun > 0)
{
if (CurrentRunningThreads < MaxThreadsRunning)
{
options[0] = ;
options[1] = bla;
BackgroundWorker myThread = new BackgroundWorker();
myThread.DoWork += new DoWorkEventHandler(backgroundWorkerRemoteProcess_DoWork);
myThread.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorkerRemoteProcess_RunWorkerCompleted);
myThread.ProgressChanged += new ProgressChangedEventHandler(backgroundWorkerRemoteProcess_ProgressChanged);
myThread.WorkerReportsProgress = true;
myThread.WorkerSupportsCancellation = true;
// THIS IS THE IMPORTANT CHANGE
myThread.RunWorkerAsync(new string[2] { list_test[i], bla });
CurrentRunningThreads++;
i++;
LeftToRun--;
}
}
}
This way each BackgroundWorker
will receive a different string[]
as its parameter, so there's no chance that two workers will get the same value.
精彩评论