使用CopyToAsync时FileStream使用块无法正确处理文件

问题描述 投票:1回答:1

我有一种情况需要将一小部分文件异步移动到网络上的另一个位置。我可以使用以下方法来执行此操作,但是在尝试删除源文件时,它有时会引发IO异常(无法访问文件x,因为它正在被另一个进程使用)。我希望using块可以帮我处理FileStreams,所以不确定发生了什么。

public static async Task MoveFileAsync(string sourceFile, string destinationFile)
    {
        using (var sourceStream = new FileStream(sourceFile, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.Asynchronous | FileOptions.SequentialScan))
        using (var destinationStream = new FileStream(destinationFile, FileMode.CreateNew, FileAccess.Write, FileShare.None, 4096, FileOptions.Asynchronous | FileOptions.SequentialScan))
        {
            await sourceStream.CopyToAsync(destinationStream);
        }

        File.Delete(sourceFile);
    }

我尝试在Parallel.ForEach循环中使用File.Move进行此操作,但发现上述方法在我的测试中要快得多。任何可能发生的事情的指针将不胜感激。

c# async-await io
1个回答
0
投票

您需要创建AsyncDisposal

见下文

using System;
using System.Threading.Tasks;
class Program
{
    static void Main() => new Program().Run().Wait();
    async Task Run()
    {
        Console.WriteLine("Before Using");
        await Async.Using(new Test(), t =>
        {
            Console.WriteLine("É só você não matar, não roubar, não estuprar, não sequestrar, não praticar latrocínio, que tu não vai pra lá, PORRA! ");
            throw new Exception("Oops");
        });
        Console.WriteLine("After Using");
    }
}

class Test : IAsyncDisposable
{
    public async Task DisposeAsync()
    {
        Console.WriteLine("Disposing...");
        await Task.Delay(1000);
        Console.WriteLine("Disposal complete");
    }
}

public interface IAsyncDisposable
{
    Task DisposeAsync();
}

public static class Async
{

    public static async Task Using<TResource>(TResource resource, Func<TResource, Task> body) where TResource : IAsyncDisposable
    {
        try
        {
            await body(resource);
        }
        finally
        {
            await resource.DisposeAsync();
        }
    }
}

好运!

© www.soinside.com 2019 - 2024. All rights reserved.