在 for 循环和范围界定中创建数组时遇到问题

Having trouble with creating arrays in a for loop and scoping

我必须为数组的成员(我不知道这是不是正确的术语)赋值。我 delcared 我的数组成员如下:(所有这些代码都在 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 此代码在 public class 内。 我认为当我在 class 中完成所有数组制作时,我将不再有变量范围的问题。但是我错了。当 bwCA[i].IsBusy == true 运行时,我仍然得到错误 nullReferenceException。也可能在 for 循环之外的任何东西运行时。

我知道我不能在循环外使用 bwCA[i] ,但我该如何更改它,以便我可以在代码中的其他地方访问 bwCA[i] (任何地方)(比如在 "else // DoSecond)?

顺便说一句。我不想使用 List

您需要将数组创建移到循环之外

// here for instance
bwCA = new BackgroundWorker[NumbwCA];

if (doFirst)
{
    for (int i = 0; i < NumbwCA; i++)
    {
        string strpara = (numbwCA.ToString()); 
       // bwCA = new BackgroundWorker[NumbwCA];

这仍然留下一些清理问题,运行 这个初始化程序两次。

更一般地说,尽量避免 static 的东西,你一开始就不应该需要 25 个后台工作者。

任务可能更合适,但我们无法判断。