c# 等待一个任务

在我的企业应用程序中,我需要每 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”


哈士奇WWW
浏览 84回答 1
1回答

互换的青春

您没有返回Result.Taskpublic static bool FileExists(string path, int timeout = 2000){&nbsp; &nbsp; Task<bool> task = Task.Run(() => File.Exists(path));&nbsp; &nbsp; return task.Wait(timeout)) && task.Result;}false如果Task失败或Resultis 则返回false。true如果Task成功并且 是Result则 返回true。
打开App,查看更多内容
随时随地看视频慕课网APP