我想异步复制多个文件,但我收到此错误,
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);
如果我调试那么我不会收到此错误?
答案 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);
}
}
}