gpt4 book ai didi

c# - 休眠直到文件存在/创建

转载 作者:行者123 更新时间:2023-12-02 01:03:01 25 4
gpt4 key购买 nike

引用我看过 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);
}
}

不知何故,我的这段代码似乎不起作用。可能是什么原因?

最佳答案

不确定哪个部分不工作。您是否意识到您的循环将运行 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));
}

关于c# - 休眠直到文件存在/创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26286086/

25 4 0
文章推荐: html - 在 中使用