作为参考,我看过 有没有办法检查文件是否正在使用? 以及如何等到 File.Exists?
但我想避免使用 SystemWatcher,因为它似乎有点过头了。我的应用程序正在调用 cmd prompt 来创建一个文件,因为我的应用程序无法知道它何时完成,只要该文件不存在,我就想使用 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);
}
}
Run Code Online (Sandbox Code Playgroud)
不知何故,我的这段代码似乎不起作用。可能是什么原因?
不确定哪个部分不起作用。您是否意识到您的循环将运行 60,000 秒(16.67 小时)?您每秒递增一次并等待它达到 60000。
尝试这样的事情:
const string filename = @"D:\Public\Temp\temp.txt";
// Set timeout to the time you want to quit (one minute from now)
var timeout = DateTime.Now.Add(TimeSpan.FromMinutes(1));
while (!File.Exists(filename))
{
if (DateTime.Now > timeout)
{
Logger("Application timeout; app_boxed could not be created; try again");
Environment.Exit(0);
}
Thread.Sleep(TimeSpan.FromSeconds(1));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5452 次 |
| 最近记录: |