将此代码转换为任务以在另一个线程上异步运行

时间:2013-08-22 06:24:30

标签: c# multithreading asynchronous task

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

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>是不可等的。

1 个答案:

答案 0 :(得分:6)

您没有在方法中调用任何异步函数,因此首先将其标记为async是没有意义的。但是,您可以使用异步版CopyTo

,而不是使用同步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;
    }
}

..没有async / await:

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);
    }
}