技术开发 频道

C#编程:如何实现多线程文件传输

  合并文件的线程hbfile定义在Form1类中,定义如下:

  public void hbfile()

  {

  
while (true)//等待

  {

  hb
=true;

  
for (int i=0;i

  {

  
if (threadw[i]==false)//有未结束线程,等待

  {

  hb
=false;

  Thread.Sleep (
100);

  break;

  }

  }

  
if (hb==true)//所有线程均已结束,停止等待,

  {

  break;

  }

  }

  FileStream fs;
//开始合并

  FileStream fstemp;

  
int readfile;

  
byte[] bytes=new byte[512];

  fs
=new FileStream (textBox3.Text .Trim ().ToString (),System.IO.FileMode.Create);

  
for (int k=0;k0)

  {

  fs.Write (bytes,
0,readfile);

  }

  
else

  {

  break;

  }

  }

  fstemp.Close ();

  }

  fs.Close ();

  DateTime dt
=DateTime.Now;

  textBox1.Text
=dt.ToString ();//结束时间

  MessageBox.Show (
"接收完毕!!!");

  }

  至此,一个多线程下载文件的程序就大功告成了,注意在输入本地文件名时,应按如下格式输入:“c:\\test\\httpftp\\bin\\d.htm”,因”\”后的字符在C#中是转义字符,线程数并非越大越好,一般5个线程就可以了,该程序在Visual Studio.Net 2002开发环境及Windows xp 操作系统上通过。

0
相关文章