0

我开始玩弄任务和异步等待。为了更好地处理如何转换现有代码,我想我会尝试更改同步运行的当前方法:

private bool PutFile(FileStream source, string destRemoteFilename, bool overwrite)
{
    if (string.IsNullOrEmpty(destRemoteFilename)) return false;
    string path = Path.GetDirectoryName(destRemoteFilename);
    if (path == null) return false;
    if (!Directory.Exists(path)) Directory.CreateDirectory(path);
    if (overwrite)
    {
        if (File.Exists(destRemoteFilename)) //delete file if it exists, because we are going to write a new one                 File.Delete(destRemoteFilename);
    }
    else if (File.Exists(destRemoteFilename)) return false;
    using (FileStream dest = File.OpenWrite(destRemoteFilename))
    {
        source.Seek(0, SeekOrigin.Begin);
        source.CopyTo(dest);
    }
    return true;
}

我试图简单地将方法更改为async, 并涉足,Task<bool>但我显然在这里遗漏了一些东西,因为它们似乎都不起作用。我所经历Type System.Threading.Task<bool>的是不可等待的。

4

1 回答 1

6

您没有在方法中调用任何异步函数,因此首先标记它没有任何意义asyncCopyTo但是,您可以使用异步版本而不是使用同步版本CopyToAsync

private static async Task<bool> PutFile(FileStream source, string destRemoteFilename, bool overwrite)
{
    if(string.IsNullOrWhiteSpace(destRemoteFilename))
        return false;

    var path = Path.GetDirectoryName(destRemoteFilename);

    if(path == null) 
        return false;

    if(!Directory.Exists(path))
        Directory.CreateDirectory(path);

    if (overwrite)
        if (!File.Exists(destRemoteFilename))
            return false;
        else
            File.Delete(destRemoteFilename);

    using (var dest = File.OpenWrite(destRemoteFilename))
    {
        source.Seek(0, SeekOrigin.Begin);
        await source.CopyToAsync(dest);

        return true;
    }
}

..并且没有异步/等待:

private static Task<bool> PutFile(FileStream source, string destRemoteFilename, bool overwrite)
{
    if (string.IsNullOrWhiteSpace(destRemoteFilename))
        return Task.Factory.StartNew(() => false);

    var path = Path.GetDirectoryName(destRemoteFilename);

    if(path == null)
        return Task.Factory.StartNew(() => false);

    if(!Directory.Exists(path))
        Directory.CreateDirectory(path);

    if (overwrite)
        if (!File.Exists(destRemoteFilename))
            return Task.Factory.StartNew(() => false);
        else
            File.Delete(destRemoteFilename);

    using (var dest = File.OpenWrite(destRemoteFilename))
    {
        source.Seek(0, SeekOrigin.Begin);
        return source.CopyToAsync(dest).ContinueWith(x => true);
    }
}
于 2013-08-22T06:50:22.277 回答