第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

c# 等待一個(gè)任務(wù)

c# 等待一個(gè)任務(wù)

C#
哈士奇WWW 2022-10-23 10:17:47
在我的企業(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。


查看完整回答
反對(duì) 回復(fù) 2022-10-23
  • 1 回答
  • 0 關(guān)注
  • 95 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)