简体   繁体   English

如何解决'名称'k'在当前上下文中不存在'的错误?

[英]How to fix 'The name 'k' does not exist in the current context' error?

I only get the System.IndexOutOfRangeException error when running the solution normally but is all okay when stepping into through the whole loop. 正常运行解决方案时,我只会收到System.IndexOutOfRangeException错误,但是进入整个循环时,一切正常。

忙碌的猫

I have tried the to catch the exception but no joy. 我已经尝试过捕获异常,但没有喜悦。

private void button1_Click(object sender, EventArgs e)
        {
            for (int j = 0; j < jobs.Length; j++)
            {
                if (jobs[j].JobID == false)
                {
                    for (int k = 0; k < threads.Length; k++)
                    {
                        if (threads[k] != null)
                        {
                            if (!(threads[k].ThreadState == ThreadState.Stopped) | !(threads[k].ThreadState == ThreadState.Unstarted))
                            {
                                continue;
                            }
                        }

                        try
                        {
                            threads[k] = new Thread(() => CountUp("ftp://ftp.net" + jobs[j].FTPFolder, HomePath + jobs[j].localFolder, j));
                            threads[k].Name = "Thread " + j + "¦ ID: " + threads[k].ManagedThreadId.ToString();
                            jobs[j].JobID = true;
                            //threads[k].Start();
                            break;
                        }
                        catch (Exception exception)
                        {
                            Console.WriteLine(exception);
                            throw;
                        }

                    }
                }
            }
            StartThreads();
        }

I expect all threads in the threads[] array to be initialised if jobs[].JobID is false. 我期望如果jobs []。JobID为false,则将初始化thread []数组中的所有线程。

Below is the CountUp() method: 下面是CountUp()方法:

        private void CountUp(string ftppath,string localFile, int jobsID)
        {
            //string conf="";
            NumberThreads++;
            //string ftpPath = "ftp://ftp.Rxsystems.net" + conf.Split('¦')[1];
            //string downloadPath = HomePath + conf.Split('¦')[0] + "\\";

            string ftpPath = ftppath;
            string downloadPath = localFile;

            List<string> MSI = new List<string>(KD.FTP.Class.ListFiles(ftpPath,
                FTPuser, FTPpass));

            if (MSI.Count > 0)
            {
                KD.File.Class.Logger(Thread.CurrentThread.Name + ", " + MSI.Count + " Files in " + ftpPath, CurDir + "\\log.txt");

                this.textBox1.AppendText(Thread.CurrentThread.Name + ", " + MSI.Count + " Files in " + ftpPath);
                //this.textBox1.AppendText("\n\r");
                int count = 0;
                foreach (string ftpFile in MSI)
                {
                    KD.FTP.Class.Download(ftpPath + ftpFile,downloadPath + "\\" + ftpFile, FTPuser,FTPpass);
                    count++;
                    KD.File.Class.Logger(Thread.CurrentThread.Name + ", " + "Downloaded " + count + "/" + MSI.Count + " Files - " + ftpFile, CurDir + "\\log.txt");
                    this.textBox1.AppendText(Thread.CurrentThread.Name + ", " + "Downloaded " + count + "/" + MSI.Count + " Files - " + ftpFile);
                    //this.textBox1.AppendText("\n\r");
                }
            }


            NumberThreads--;
            jobs[jobsID].JobID = false;
        }

The below initialises threads[] and jobs[]: 下面初始化线程[]和作业[]:

private void Form1_Load(object sender, EventArgs e)
        {
            Form1.CheckForIllegalCrossThreadCalls = false;

            if (File.Exists(CurDir + "\\FTPpaths.config"))
            {
                foreach (string line in File.ReadAllLines(CurDir + "\\FTPpaths.config"))
                {
                    if (!string.IsNullOrEmpty(line))
                    {
                        ConfigPaths.Add(line.Split('¦')[0] + "¦" + line.Split('¦')[1]);
                    }
                }

                if (ConfigPaths.Count > 0)
                {
                    jobs = new Jobs[ConfigPaths.Count];

                    for (int j = 0; j < ConfigPaths.Count; j++)
                    {
                        jobs[j] = new Jobs();
                        jobs[j].FTPFolder = ConfigPaths[j].Split('¦')[1];
                        jobs[j].localFolder = ConfigPaths[j].Split('¦')[0];
                        jobs[j].JobID = false;
                    }

                    threads = new Thread[jobs.Length];

                }


                timer1.Enabled = true;
            }
            else
            {
                Application.Exit();
            }
        }

From what I can see the problem is with j variable which is captured from closure into delegate passed to new Thread . 从我可以看到的问题是j变量,它从闭包捕获到传递给new Thread委托中。 It's well know problem when actual delegate execution references the variable in state after the loop execution so it's supposed to effectively contain jobs.Length value which is out of range. 众所周知,实际的委托执行在循环执行后引用状态变量的问题,因此应该有效地包含jobs.Length值超出范围。 To fix you need to introduce a local variable inside the loop to copy j value in, and then use this variable instead of j as index of jobs inside the delegate passed to the Thread constructor: 要解决此问题,您需要在循环内引入一个局部变量以复制j值,然后使用此变量而不是j作为传递给Thread构造函数的委托中的jobs索引:

try
{
    var jobIdx = j;
    threads[k] = new Thread(() => CountUp("ftp://ftp.net" + jobs[jobIdx].FTPFolder, HomePath + jobs[jobIdx].localFolder, jobIdx));
    ...
    // other stuff

}
catch (Exception exception)
{
    Console.WriteLine(exception);
    throw;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当前上下文中不存在如何解决名称“名称”和“值”的问题 - How to fix the name 'Name' & 'Value' does not exist in the current context 当前上下文中不存在名称“Fix” - The name 'Fix' does not exist in the current context 如何修复“当前上下文中不存在名称‘脚本’”? - how do I fix "The name 'script' does not exist in the current context"? 如何解决&#39;当前上下文中不存在&#39;WebSecurity&#39;这个名字&#39;? - How to fix 'The name 'WebSecurity' does not exist in the current context'? 如何解决“当前上下文中不存在名称&#39;页面&#39;” - How do I fix “The name 'page' does not exist in the current context” 如何在 C# Windows 应用程序中修复“名称......在当前上下文错误中不存在”? - How to fix "the name ... does not exist in the current context error" in a C# Windows Application? 错误:名称“名称”在当前上下文中不存在 - Error: The name 'Name' does not exist in the current context 类型或名称空间名称“ K”在当前上下文中不存在 - The type or namespace name 'K' does not exist in the current context 如何解决“名称***在当前上下文中不存在”错误? - How to resolve “The name *** does not exist in the current context” error? 如何避免“当前上下文中不存在名称'ConfigurationManager'”错误? - How to avoid “The name 'ConfigurationManager' does not exist in the current context” error?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM