【问题标题】:for loop keeps making my program crash c#for循环不断使我的程序崩溃c#
【发布时间】:2016-08-23 13:43:06
【问题描述】:

我有一个将固件编程到电路板的应用程序。在应用程序中,您可以对单个板或托盘进行编程。对托盘进行编程时,一次只能装载 14 个。 用户可能想要对 30 个板进行编程,所以我希望程序对 14 个板进行编程,然后告诉用户他们需要重新加载托盘。 目前我只有一个板子可以练习,所以我只是在重新编程同一个板子,假装它是一个托盘。 我尝试使用循环来解决这个问题,但是当我按下开始按钮时,它全部冻结并停止响应。

以下是我的代码:

    private void setFirmwareMultiple()
    {
        clearTicksandCrosses();
        string firmwareLocation = Firmware(productComboBox.Text); //get the firmware location
        string STPath = @"C:\Users\Falconex\Documents\FalconexTest\FalconexTest\ST-LINK Utility\ST-LINK_CLI.exe"; //file location

        string result; //set string
        string result2; //set string 
        int counter = 0;


        int numberOfBoards = int.Parse(numberOfBoardsTextBox.Text);
        while (numberOfBoards > counter) { 

          for (int i = 0; i > 14; i = i + 1) { 
        ProcessStartInfo start = new ProcessStartInfo(); //new process start info
        start.FileName = STPath; //set file name
        start.Arguments = "-C -ME -p " + firmwareLocation + " -v -Run"; //set arguments
        start.UseShellExecute = false; //set shell execute (need this to redirect output)
        start.RedirectStandardOutput = true; //redirect output
        start.RedirectStandardInput = true; //redirect input
        start.WindowStyle = ProcessWindowStyle.Hidden; //hide window
        start.CreateNoWindow = true; //create no window
                string picNumber = i.ToString();

        using (Process process = Process.Start(start)) //create process
        {
            programmingTextBlock.Text = "Board Programming...";
            System.Windows.Application.Current.Dispatcher.Invoke(DispatcherPriority.Background,
                                  new Action(delegate { }));

            try
            {

                while (process.HasExited == false) //while open
                {
                    process.StandardInput.WriteLine(); //send enter key

                }

                using (StreamReader reader = process.StandardOutput) //create stream reader
                {
                    result = reader.ReadToEnd(); //read till end of process
                    File.WriteAllText("File.txt", result); //write to file
                }
                saveReport();
            }
            catch { } //so doesn't blow up
            finally
            {
                int code = process.ExitCode; //get exit code
                codee = code.ToString(); //set code to string
                File.WriteAllText("Code.txt", codee); //save code

                if (code == 0)
                {
                    tick1.Visibility = Visibility.Visible;
                            counter = counter + 1;
                }
              else
                        {
                            cross1.Visibility = Visibility.Visible;
                        }

                programmingTextBlock.Text = "";

                    }
                }

                System.Windows.MessageBox.Show("Load new boards");

        }
    }
    }

我已将用户想要的板总数放入 for 循环中。

我认为这可能与 for 循环有关。因为一开始,在 for 循环中,我不小心放了 (i

任何帮助将不胜感激!

提前谢谢你, 露西

【问题讨论】:

  • for 循环中的条件是 continue 条件。所以只有i > 14 才会进入循环,因为它是用0 初始化的,所以它永远不会发生。所以你与i <14 的“意外”实际上是正确的。乍一看无法说出为什么它没有停止。请花时间编辑您的问题并格式化代码以提高可读性。
  • for 循环中的任何代码都不会被执行。因此你有一个无限的while循环。
  • 好的,谢谢!我马上试试
  • 那么我会将 i 设置为什么?我很困惑
  • 您拥有while (numberOfBoards > counter) { for (int i = 0; i > 14; i = i + 1) { ,因此对于每次迭代,您将运行它 14 次,并且仅当返回码为零时计数器才会增加。 numberOfBoards 是什么值,并使用调试器单步执行,看看计数器是否在增加。

标签: c# loops for-loop


【解决方案1】:

就目前的代码而言,for 循环的内容永远不会被执行。 for 循环中的条件是 continue 条件。因为i 是用0 初始化的,所以条件i > 14 永远不会满足。所以结果是一个无限的外部while 循环。

您与i < 14 发生的第一个“意外”是正确的。但是循环并没有停止,因为你的内部 while 循环永远不会结束:

while (process.HasExited == false) //while open
{
    process.StandardInput.WriteLine(); //send enter key
}

首先,请不要将booltruefalse 进行比较。一个简单的while (!process.HasExited) 就足够了。

其次,您必须 refresh 您的流程实例才能正确更新 HasExited 属性:

while (!process.HasExited) //while open
{
    process.StandardInput.WriteLine(); //send enter key
    process.Refresh(); // update the process's properties!
}

您也可以考虑在该循环中添加Thread.Sleep(...)

【讨论】:

  • 仍然冻结:(
  • @lucycopp 你确认进程确实退出了吗?
  • 当我通过调试器时,它甚至没有进入 for 循环,它到达 i
  • @lucycopp,这是不可能的。 i
  • 我通过了调试器但没有
【解决方案2】:

答案很简单:

while (numberOfBoards > counter) { 

      for (int i = 0; i > 14; i = i + 1) { 

在上面的代码中,永远不会执行 for 循环,因为 i 总是小于 14。

因此,计数器永远不会增加,而且,while 永远不会结束。

但除此之外,您的循环方法是错误的。下面的例子(完全测试程序)是你应该做的事情:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int counter = 0;
            int i = 0;
            int numberOfBoards = 35;

            for (; numberOfBoards > counter; i++, counter++)
            {
                Console.WriteLine("Counter {0}/i {1}", counter, i);

                //call your thread here.
                //make sure that he exists.
                //use somekind of timeout to finish
                //alert the user in case of failure but move to the next anyway to avoid an infinite looping.

                if (i == 13) i = 0;
            }

            Console.WriteLine("Press any key");
            Console.ReadKey();
        }
    }
}

【讨论】:

  • @lucycopp,因为您正在递增“finally”块内的“计数器”,但只有在发生异常时才会执行......
  • 这不是真的,finally 块的全部意义是在每个 情况下执行。冻结的原因是内部的while循环。看我的回答
  • 你写的是@RenéVogt。很抱歉造成误解。
猜你喜欢
  • 1970-01-01
  • 2017-11-23
  • 2014-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多