Reputation: 520
I have to assign values to members(I don't know if this is the right term) of an array. I delcared my array members as follow: (all this code is inside a public class BWClass)
public static BackgroundWorker[] bwCA = new BackgroundWorker[25];
public static int NumbwCA;
private static bool HasRunOnce = false;
public static void BackgroundWorkerInitializer(bool doFirst, int numbwCA)
{
// Okay we got here. So we can presume that array checking (number not exceeding the array) is already done
if (!HasRunOnce)
{
NumbwCA = numbwCA; // for access
} // Now it is impossible to stop less backgroundworkers then started later on in the code
if (doFirst)
{
for (int i = 0; i < NumbwCA; i++)
{
string strpara = (numbwCA.ToString()); // Could also directly write numbwCA.ToString() directly in the RunWorkerAsync() method
bwCA = new BackgroundWorker[NumbwCA];
bwCA[i] = new BackgroundWorker();
bwCA[i].WorkerReportsProgress = true;
bwCA[i].WorkerSupportsCancellation = true;
bwCA[i].DoWork += new DoWorkEventHandler(bwa_DoWork);
bwCA[i].ProgressChanged += new ProgressChangedEventHandler(bwa_ProgressChanged);
bwCA[i].RunWorkerCompleted += new RunWorkerCompletedEventHandler(bwa_RunWorkerCompleted);
bwCA[i].RunWorkerAsync(strpara);
}
}
else // DoSecond
{
// stop the backgroundworkers
for (int i = 0; i < NumbwCA; i++)
{
if (bwCA[i].IsBusy == true)
{
bwCA[i].CancelAsync();
HasRunOnce = false; // If restarting the server is required. The user won't have to restart the progrem then
}
else
{
Console.WriteLine(">>The backgroundworkers are already finished and don't need canceling");
}
}
}
}
Al this code is inside a public class. I thought that when I do all the array making in a class I won't have the problem of variable scopes anymore. But I was wrong. I still get the Error nullReferenceException when the bwCA[i].IsBusy == true runs. Probably also when anything outside the for loop runs.
I know that I can't use the bwCA[i] outside the loop were it is declared but how do I change this, so that I can access bwCA[i] (anywhere) else in the code (like in the "else // DoSecond)?
btw. I prefer not to use a List
Upvotes: 0
Views: 37
Reputation: 273179
You need to move the array creation outside the loop
// here for instance
bwCA = new BackgroundWorker[NumbwCA];
if (doFirst)
{
for (int i = 0; i < NumbwCA; i++)
{
string strpara = (numbwCA.ToString());
// bwCA = new BackgroundWorker[NumbwCA];
That still leaves a few issues with cleanup and running this Initializer twice.
More general, try to avoid static
stuff and you shouldn't be needing 25 Backgroundworkers in the first place.
Tasks are probably more appropriate but we can't tell.
Upvotes: 1