在异步复制文件时获取“无法访问已关闭的文件”

时间:2014-09-18 08:39:39

标签: c# .net task-parallel-library async-await

我想异步复制多个文件,但我收到此错误,

System.ObjectDisposedException: Cannot access a closed file.

这是我的方法,

public Task CopyAllAsync(IList<ProductsImage> productsImage)
{
    var tasks = new List<Task>();
    foreach (var productImage in productsImage)
    {
        var task = _fileService.CopyAsync(productImage.ExistingFileName, productImage.NewFileName);
        tasks.Add(task);
    }
    return Task.WhenAll(tasks);
}

这是FileService.CopyAsync方法,

public Task CopyAsync(string sourcePath, string destinationPath)
{
    using (var source = File.Open(sourcePath, FileMode.Open))
    {
        using (var destination = File.Create(destinationPath))
        {
            return source.CopyToAsync(destination);
        }
    }
}

然后我在等待这个,

await _imageService.CopyAllAsync(productsImage);

如果我调试那么我不会收到此错误?

1 个答案:

答案 0 :(得分:6)

您需要await复制操作,而不是简单地返回任务。这样可以确保您不会过早结束使用范围,这意味着在Dispose上调用FileStream

public async Task CopyAsync(string sourcePath, string destinationPath)
{
    using (var source = File.Open(sourcePath, FileMode.Open))
    {
        using (var destination = File.Create(destinationPath))
        {
            await source.CopyToAsync(destination);
        }
    }
}