【问题标题】:C# while loop runs inconsistently [closed]C#while循环运行不一致[关闭]
【发布时间】:2018-02-23 21:29:44
【问题描述】:

我有这个代码:

string winpath = Environment.GetEnvironmentVariable("C:");
int i = 0;

Console.WriteLine("How much would you like to destroy your pc?");

i = Convert.ToInt32(Console.ReadLine());
int j = 0;

while (j < i)
{
    Process.Start(winpath + @"\Windows\System32\calc.exe");
    j++;
}

我想让用户选择打开多少个计算器,我输入1,得到一个计算器,输入2,我仍然得到一个计算器,输入3得到一个计算器,输入5得到2个计算器。我也尝试了 for 循环,但结果相同。

【问题讨论】:

  • 始终使用Path.Combine 连接您的路径字符串。
  • 另外,System32 会在搜索路径上,所以你只需要Process.Start("calc.exe")
  • 那么您的实际问题是什么?你的代码不符合你的要求,但你没有说什么是“不一致”。

标签: c# for-loop while-loop


【解决方案1】:

您的问题不在于循环本身,而是您需要计算循环的最大值。 查看您的代码并根据您对基于输入数字的 calc 实例数的描述,您需要使用整数除法:

i = Convert.ToInt32(Console.ReadLine());
int j = 0;
while (j < i / 2)
{
    ...
}

【讨论】:

    【解决方案2】:

    您很可能需要在启动进程之间添加一个短暂的延迟。 while 循环运行得如此之快,以至于 Windows 无法及时响应进程启动请求。

    尝试在每个Process.Start() 之后添加Thread.Sleep()

    using System.Threading;
    
    for (int i = 0; i < total; i++)
    {
        Process.Start("calc.exe"); // anything in /system32 is already on the path
        Thread.Sleep(100); // 100 milliseconds
    }
    

    【讨论】:

    • 这行得通,虽然我使用了 1000 毫秒的延迟,谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-18
    相关资源
    最近更新 更多