【问题标题】:Having trouble with creating arrays in a for loop and scoping在 for 循环和范围内创建数组时遇到问题
【发布时间】:2016-02-16 02:23:31
【问题描述】:

我必须为数组的成员(我不知道这是否正确)赋值。我将我的数组成员定义如下:(所有这些代码都在公共类 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 运行时,我仍然收到错误 nullReferenceException。也可能在 for 循环之外的任何内容运行时。

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

顺便说一句。我不喜欢使用列表

【问题讨论】:

    标签: c# arrays loops scope nullreferenceexception


    【解决方案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 来处理 tcpclients。但我相信这里的任务更合适。谢谢
    猜你喜欢
    • 2023-04-04
    • 1970-01-01
    • 2021-09-09
    • 2017-06-02
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多