在我的应用程序中,我有一个带有字段的对象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 ,但这似乎使它永远锁定。
在条件语句中使用 OR 运算符时,如果第一个条件为 TRUE,则其余条件将被跳过。
在您的情况下,DateTime.Now - startTime < TimeSpan.FromSeconds(...)在一段时间内始终为真。
我建议你可以这样实现
//do until true or timeout reached.
while (!directoryInfo.Exists) {
if (DateTime.Now - startTime > TimeSpan.FromSeconds(Convert.ToInt32(DependentPCTimeout)))
break;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句