在我的企業(yè)應(yīng)用程序中,我需要每 800 毫秒檢查一次文件是否存在(主要通過網(wǎng)絡(luò))。當(dāng)前工作正常的方法是這樣的: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; }}問題是如果找不到路徑,則凍結(jié) 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;} 問題是我的任務(wù)沒有按預(yù)期等待,似乎沒有使用超時(shí)。這種方法對(duì)于使用任務(wù)/等待是否正確?文件格式如“\\10.100.100.1\status.txt”
1 回答

互換的青春
TA貢獻(xiàn)1797條經(jīng)驗(yàn) 獲得超6個(gè)贊
您沒有返回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 關(guān)注
- 95 瀏覽
添加回答
舉報(bào)
0/150
提交
取消