在for循环和作用域中创建数组时遇到问题
本文关键字:数组 遇到 问题 创建 for 循环 作用域 | 更新日期: 2023-09-27 18:21:52
我必须为数组的成员赋值(我不知道这是否是正确的术语)。我将数组成员如下所示:(所有这些代码都在公共类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");
}
}
}
}
所有这些代码都在一个公共类中。我想,当我在一个类中完成所有的数组制作时,我就不会再遇到变量作用域的问题了。但我错了。当bwCA[I].IsBusy=true运行时,我仍然会得到Error nullReferenceException。也可能是当for循环之外的任何东西运行时。
我知道如果声明了bwCA[I],我就不能在循环外使用它,但我该如何更改它,以便我可以访问代码中的其他任何地方(如"else//DoSecond"中)?
顺便说一句。我不喜欢使用列表
您需要将数组创建移动到循环之外
// here for instance
bwCA = new BackgroundWorker[NumbwCA];
if (doFirst)
{
for (int i = 0; i < NumbwCA; i++)
{
string strpara = (numbwCA.ToString());
// bwCA = new BackgroundWorker[NumbwCA];
这仍然留下了一些清理和运行此Initializer两次的问题。
一般来说,尽量避免static
的东西,你一开始就不应该需要25名后台工作人员。
任务可能更合适,但我们无法判断。