在我的企業應用程序中,我需要每 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”
1 回答
互換的青春
TA貢獻1797條經驗 獲得超6個贊
您沒有返回Result.Task
public static bool FileExists(string path, int timeout = 2000)
{
Task<bool> task = Task.Run(() => File.Exists(path));
return task.Wait(timeout)) && task.Result;
}
false如果Task失敗或Resultis 則返回false。
true如果Task成功并且 是Result則 返回true。
- 1 回答
- 0 關注
- 114 瀏覽
添加回答
舉報
0/150
提交
取消
