循环直到满足条件或时间已过

时间:2017-11-10 13:10:16

标签: c#

在我的应用程序中,我有一个字段DependentPC的对象,它可以保存IP地址或网络共享。如果它是一个IP地址,它会执行一个简单的Ping并存储结果,但如果它是一个网络共享,我需要它继续检查共享,直到它存在或经过指定的时间。这是我到目前为止所得到的:

//Determines if it's a network share or not.
if (appToRun.DependentPC.Contains(@"\"))
{
    var startTime = DateTime.Now;
    var directoryInfo = new DirectoryInfo(appToRun.DependentPC);

    //do until true or timeout reached.
    while (DateTime.Now - startTime < TimeSpan.FromSeconds(Convert.ToInt32(DependentPCTimeout)) || !directoryInfo.Exists) { }

    if (!directoryInfo.Exists)
    {
        XtraMessageBox.Show($"Could not find or get a reply from the computer share '{appToRun.DependentPC}'. ", $"{appToRun.DependentPC} Not Found", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        return false;
    }
}
else
{
    //Ping computer.
    if (PingComputer(appToRun.DependentPC) != IPStatus.Success)
    {
        XtraMessageBox.Show($"Could not find or get a reply from the computer '{appToRun.DependentPC}'. ", $"{appToRun.DependentPC} Not Found", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        return false;
    }
}

变量DependentPCTimeout的值为50,网络共享为“\ 192.168.103.100 \ WorkingFolder。所以这一点有效。当使用网络共享时,它似乎总是等到时间在继续之前已经过去了,即使目录存在。我尝试使用带有while循环的单个OR |,但这似乎使它永远锁定。

2 个答案:

答案 0 :(得分:2)

在条件语句中使用OR运算符时,如果第一个条件为TRUE,则跳过其余条件。

在您的情况下, DateTime.Now - startTime&lt; TimeSpan.FromSeconds(...)在一段时间内始终为真。

我建议您可以像这样实施

//do until true or timeout reached.
  while (!directoryInfo.Exists) { 
    if (DateTime.Now - startTime > TimeSpan.FromSeconds(Convert.ToInt32(DependentPCTimeout)))
        break;
  }

答案 1 :(得分:0)

您需要检查两个条件都是真的,而不是其中一个条件为真。所以你需要使用AND而不是OR:

//Determines if it's a network share or not.
if (appToRun.DependentPC.Contains(@"\"))
{
    var startTime = DateTime.Now;
    var directoryInfo = new DirectoryInfo(appToRun.DependentPC);

    //wait until directory exists or timeout reached.
    while (DateTime.Now - startTime < TimeSpan.FromSeconds(Convert.ToInt32(DependentPCTimeout)) && !directoryInfo.Exists) { }

    if (!directoryInfo.Exists)
    {
        XtraMessageBox.Show($"Could not find or get a reply from the computer share '{appToRun.DependentPC}'. ", $"{appToRun.DependentPC} Not Found", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        return false;
    }
}
else
{
    //Ping computer.
    if (PingComputer(appToRun.DependentPC) != IPStatus.Success)
    {
        XtraMessageBox.Show($"Could not find or get a reply from the computer '{appToRun.DependentPC}'. ", $"{appToRun.DependentPC} Not Found", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        return false;
    }
}
相关问题