亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

c# 等待一個任務

c# 等待一個任務

C#
哈士奇WWW 2022-10-23 10:17:47
在我的企業應用程序中,我需要每 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。


查看完整回答
反對 回復 2022-10-23
  • 1 回答
  • 0 關注
  • 114 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號