在for循环和作用域中创建数组时遇到问题

时间:2015-11-14 16:43:43

标签: c# arrays loops scope nullreferenceexception

我必须为数组的成员分配值(我不知道这是否是正确的术语)。我按照以下方式对数组成员进行了描述:(所有这些代码都在公共类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]它是如何声明但是我如何更改它,以便我可以访问代码中的bwCA [i](任何地方)其他地方(例如“否则// DoSecond?”

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

1 个答案:

答案 0 :(得分:1)

您需要在循环外部移动数组

// 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个Backgroundworkers。

任务可能更合适,但我们无法分辨。