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

use*_*567 1 .net c# task-parallel-library async-await

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

System.ObjectDisposedException: Cannot access a closed file.
Run Code Online (Sandbox Code Playgroud)

这是我的方法,

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);
}
Run Code Online (Sandbox Code Playgroud)

这是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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我在等待这个,

await _imageService.CopyAllAsync(productsImage);
Run Code Online (Sandbox Code Playgroud)

如果我调试然后我不会得到这个错误?

i3a*_*non 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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @ user960567测试一下. (2认同)