C#中的非阻塞文件复制 [英] Non-blocking file copy in C#

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

问题描述

如何在不阻塞线程的情况下用C#复制文件?

How can I copy a file in C# without blocking a thread?

推荐答案

异步编程的思想是允许调用线程(假设它是线程池线程)返回到线程池以在异步时用于其他任务IO完成.在幕后,调用上下文填充到数据结构中,并且有1个或多个IO完成线程监视等待完成的调用. IO完成后,完成线程将调用回到恢复调用上下文的线程池中.这样,只有100个完成线程和几个线程池线程(大部分处于空闲状态),而不是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.

我能想到的最好的方法是:

The best I can come up with is:

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

我还没有对此进行全面的性能测试.我有点担心,因为如果这么简单,它将已经存在于核心库中.

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.

await做我在幕后描述的事情.如果您想大致了解它是如何工作的,那么可能会有助于理解Jeff Richter的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天全站免登陆