在我的企业应用程序中,我需要每 800 毫秒检查一次文件是否存在(主要通过网络)。当前工作正常的方法是这样的:
private delegate bool FileExistsDelegate(string file);
public static bool FileExists(string path, int timeout = 2000)
{
bool retValue = false;
try
{
FileExistsDelegate callback = new FileExistsDelegate(File.Exists);
IAsyncResult result = callback.BeginInvoke(path, null, null);
if (result.AsyncWaitHandle.WaitOne(timeout, false))
return callback.EndInvoke(result);
return false;
}
catch
{
return false;
}
}
问题是如果找不到路径,则冻结 UI,因此我使用 Task 将其重写为:
public static bool FileExists(string path, int timeout = 2000)
{
Func<bool> func = () => File.Exists(path);
Task<bool> task = new Task<bool>(func);
task.Start();
if (task.Wait(timeout))
{
return true;
}
return false;
}
问题是我的任务没有按预期等待,似乎没有使用超时。这种方法对于使用任务/等待是否正确?文件格式如“\\10.100.100.1\status.txt”
互换的青春
相关分类