如何在C#中以高效的方式使用File.Copy()复制文件? [英] How Do I Copy A File Using File.Copy() In An Efficient Manner In C#?

查看:718
本文介绍了如何在C#中以高效的方式使用File.Copy()复制文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用File.copy(source,dest,bool)将文件从一个位置复制到另一个位置。我面临的问题是源文件的大小(1.5 GB)和我的用户界面(窗体)进入无响应状态,只有在复制完成后才会恢复。

我如何以更有效的方式实现它?



请帮助!!!

谢谢:)

Hi, i am copying a file from one location to another using File.copy(source, dest, bool). The problem i am facing is that the source file is of huge size(1.5 GB) and my User Interface(form) goes into a "not responding" state and resumes only when the copying gets completed.
How do i achieve it in a more efficient manner?

Please help!!!
Thanks :)

推荐答案

显然有人想出了一种更快捷的做事方式:

更快的File.Copy [ ^ ]



您可以查看。
Apperantly someone has figured out a faster way of doing things:
A Faster File.Copy[^]

You might check it out.






如果您使用的是.net Framework 4.5,请使用async-await。它将您的任务跨多核(如果有)并行。它与Task具有相同的实现。 .net 4.5中引入的唯一重要功能是async-await。我将告诉UI线程(Dispatcher Thread)这个进程长时间运行并且不挂起UI线程。在单独的线程中执行这行代码(任务)。



我的一位朋友(Kumar Prateek的解决方案2)为您提供了解决方案。但它完成了40%。



基本语法是





Hi,

If you are using .net Framework 4.5 then use async-await. It parallel your task across multi core (if you have). It has same implementation as Task. The only big feature introduced in .net 4.5 is async-await. I will tell UI thread (Dispatcher Thread) that this process is long running and don't hang UI thread. execute this line of code in saperate thread (Task).

One of my friend (Solution 2 by Kumar Prateek) has provided you solution. but it is 40% done.

Basic syntax is


private void async btnCopy_click(object sender, EventArg a)
{
   busyIndicator.IsBusy = true; //If any busy Indicator used.

   await CopyFile();

  busyIndicator.IsBusy=false; //turn of busy indicator
}


private Task CopyFile()
{
   return Task.Factory.StartNew(()=>{ /* Your copy implemenation*/});
}


使用BackgroundWorker线程执行复制。您甚至可以通过报告进度来更新UI。



顺便说一句,当复制处于活动状态时,用户还希望做什么其他任务?
Use a BackgroundWorker thread to perform the copy. You can even update the UI by reporting progress.

By the way, what other tasks are the user expected to do while the copying is active?


这篇关于如何在C#中以高效的方式使用File.Copy()复制文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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