异步文件复制/移动在C# [英] Asynchronous File Copy/Move in C#

查看:243
本文介绍了异步文件复制/移动在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是做文件拷贝正确的方法/ C#中异步移动?

What is the correct way to do file copy/move asynchronously in C#?

推荐答案

异步编程的想法是允许调用线程(假设它是一个线程池线程)返回线程池使用一些其他的任务,而异步IO完成。引擎盖下的呼叫上下文被装进一个数据结构和1个或多个IO完成线程监视呼叫等待完成。当完成IO完成线程调用返回到线程池恢复通话环境。通过这种方式,而不是100个线程阻塞,只有在完成线程和几个线程池中的线程坐在大多闲置。

The idea of async programming is to allow the calling thread (assuming it's a thread pool thread) to return to the thread pool for use on some other task while async IO completes. Under the hood the call context gets stuffed into a data structure and 1 or more IO completion threads monitor the call waiting for completion. When IO completes the completion thread invokes back onto a thread pool restoring the call context. That way instead of 100 threads blocking there is only the completion threads and a few thread pool threads sitting around mostly idle.

我能想出的最好的是:

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

我还没有这虽然进行了广泛的测试PERF。我有点担心,因为如果它是如此简单,将已经在核心库。

I haven't done extensive perf testing on this though. I'm a little worried because if it was that simple it would already be in the core libraries.

等待做什么我描述了幕后。如果你想获得它的工作原理,它可能有助于了解杰夫·里希特的AsyncEnumerator的总体思路。他们可能不完全线路在同一行,但想法是非常接近。如果你看一下调用堆栈从异步的方法,你会看到它的MoveNext。

await does what I am describing behind the scenes. If you want to get a general idea of how it works it would probably help to understand Jeff Richter's AsyncEnumerator. They might not be completely the same line for line but the ideas are really close. If you ever look at a call stack from an "async" method you'll see MoveNext on it.

至于此举的推移它并不需要是异步,如果它真的是一个移动,而不是再拷贝删除。此举是针对文件表快原子操作。它只能这样但如果你不尝试将文件移动到不同的分区。

As far as move goes it doesn't need to be async if it's really a "Move" and not a copy then delete. Move is a fast atomic operation against the file table. It only works that way though if you don't try to move the file to a different partition.

这篇关于异步文件复制/移动在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆