c# 非阻塞算法,C#中的非阻塞文件复制

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

解决方案

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 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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值