【发布时间】:2014-10-09 19:03:01
【问题描述】:
我看过的参考 Is there a way to check if a file is in use? 和How to wait until File.Exists?
但我想避免使用 SystemWatcher,因为它似乎有点过头了。我的应用程序正在调用 cmd 提示符来创建文件,并且由于我的应用程序无法知道文件何时完成,所以只要文件不存在,我就在考虑使用 Sleep()。
string filename = @"PathToFile\file.exe";
int counter = 0;
while(!File.Exists(filename))
{
System.Threading.Thread.Sleep(1000);
if(++counter == 60000)
{
Logger("Application timeout; app_boxed could not be created; try again");
System.Environment.Exit(0);
}
}
不知何故,我的这段代码似乎不起作用。可能是什么原因?
【问题讨论】:
-
我保证
SystemWatcher将使用比您想出的任何涉及 sleep 和 while 循环的方法更少的资源 -
这听起来像
FileSystemWatcher的确切目的。如果您编写的代码不起作用,而FileSystemWatcher确实起作用,那并不是真正“过度”的事情。 -
发生了什么? 似乎不起作用太模糊了。
-
那么你等了 60000 秒吗?
-
我也很困惑为什么你有一个计数器并且你每秒都在睡觉等待计数器达到 60000。你可以通过输入
System.Threading.Thread.Sleep(60000000)来消除所有这些。但是,我认为您想要的是System.Threading.Thread.Sleep(60000)。