C# 线程复制文件!使用进度条同时显示单个文件的复制进度,和总体进度。复制多文件(文件数量大约1000以上)时候程序假死,求高手优化

gaoyiddf 2011-07-24 10:07:17
本来我是没使用线程的,后来会假死,就是突然卡住,进度条都不动了,然后突然一会就显示备份成功,用了线程之后虽然不一定会假死,但是复制时间却是原来的两倍,所以,求高手优化,目前之是单线程,本人菜鸟,还不会用多线程!

//线程开始启动调用,主方法Copy
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
Copy(@txtSource.Text.Trim(), @txtDest.Text.Trim());
if (progressBar1.Value == progressBar1.Maximum)
{
DateTime Edt = DateTime.Now;
TimeSpan ts = Edt - Sdt;
MessageBox.Show("备份成功,共用时(" + ts.Seconds + "秒)");
count = 0;
leng = 0;

}
}
public void Copy(String source, String destination)
{
DirectoryInfo info = new DirectoryInfo(source);
foreach (FileSystemInfo fsi in info.GetFileSystemInfos())
{
//目标路径destName = 目标文件夹路径 + 原文件夹下的子文件(或文件夹)名字
//Path.Combine(string a ,string b) 为合并两个字符串
String destName = Path.Combine(destination, fsi.Name);
//如果是文件类,就复制文件
if (fsi is FileInfo)
{

lblMessge.Refresh();
lblParent.Refresh();
lblMessge.Text ="正在复制:"+ fsi.Name;
Getlength(fsi.FullName, destName);
// File.Copy(fsi.FullName, destName, true);
leng += count;
progressBar1.Value = leng;
lblParent.Text = (progressBar1.Value * 100) / progressBar1.Maximum + "%";

}
//如果不是 则为文件夹,继续调用文件夹复制函数,递归
else
{
Directory.CreateDirectory(destName);
Copy(fsi.FullName, destName);
}
}
}

private void Getlength(string sources, string destname)
{
FileStream ofile = new FileStream(sources, FileMode.Open, FileAccess.Read);
FileStream nfile = new FileStream(destname, FileMode.Create, FileAccess.Write);
progressBar2.Maximum=Convert.ToInt32(ofile.Length);
byte[] buffer = new byte[1024];
int plength = 0;
do
{
plength += ofile.Read(buffer, 0, 1024);
progressBar2.Value = plength;
nfile.Write(buffer, 0, 1024);
} while (plength < ofile.Length);
}

谁帮我看看怎么才能在复制多文件的时候不假死,如果用线程,是否能跟原来用的时间一样!
...全文
278 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
使用线程的目的不是简单地图快,而是为了让多个任务并行执行。这样总体时间减少了,但是单个任务的执行时间肯定会有所延长。

不过,长了2倍时间这还是比较可怕的。你应该检查一下你的主线程是不是干了什么不该干的事情。比如我们以前遇到这样一个小子,它为了检查窗体是否靠边(如果刚好被鼠标拖动靠边就要让窗体隐藏起来),结果他竟然搞了一个50毫秒的timer来不断检测,结果足足有好几天、在我们揪出这个害群之马之前,我们的程序都运行起来很慢。编出这类程序基本上就是出于基于显摆的态度(否则不会这样设计和测试程序的),低估了所有开发同事的测试软件性能的智商了,最后肯定会搬起石头砸自己的脚了。

110,571

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧