读书人

C#线程有关问题,为什么小弟我上传多个

发布时间: 2012-03-08 13:30:13 作者: rapoo

C#线程问题,为什么我上传多个文件时它总是上传两个就重复第二个其它的不传了
string[] path;
//窗体加载
private void ftp_Load(object sender, EventArgs e)
{
openFileDialog1.Multiselect = true;
openFileDialog1.Filter = "WAV files (*.wav)|*.wav|All files (*.*)|*.* ";
}
//浏览
private void button1_Click(object sender, EventArgs e)
{
this.openFileDialog1.ShowDialog();
path = this.openFileDialog1.FileNames;
}
//文件上传
private void button2_Click(object sender, EventArgs e)
{
this.lbl_ftpStakt.Text = "连接服务器... ";
this.lbl_ftpStakt.Visible = true;
for (i = 0; i < path.Length; i++)
{
filename = path[i].ToString();
Thread tThread = new Thread(new ThreadStart(RunsOnWorkerThread));
tThread.Start();
FileInfo p = new FileInfo(path[i].ToString());
// MessageBox.Show(p.Name);
}
}
private void RunsOnWorkerThread()
{
mt.WaitOne();
Interlocked.Increment(ref flag);
this.lbl_ftpStakt.Text = "连接服务器中... ";
FileInfo fileInf = new FileInfo(filename);


FtpWebRequest reqFTP;
// 根据uri创建FtpWebRequest对象
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri( "ftp://192.168.0.16/ " + fileInf.Name));
// ftp用户名和密码
reqFTP.Credentials = new NetworkCredential( "record ", "files ");
// 默认为true,连接不会被关闭
// 在一个命令之后被执行
reqFTP.KeepAlive = false;
// 指定执行什么命令
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
// 指定数据传输类型
reqFTP.UseBinary = true;
// 上传文件时通知服务器文件的大小
reqFTP.ContentLength = fileInf.Length;
//long _length = fileInf.Length;
// 缓冲大小设置为2kb
int buffLength = 2048; ////
byte[] buff = new byte[buffLength];
int contentLen;
// 打开一个文件流 (System.IO.FileStream) 去读上传的文件
FileStream fs = fileInf.OpenRead();
try
{
// 把上传的文件写入流
Stream strm = reqFTP.GetRequestStream();
// 每次读文件流的2kb
contentLen = fs.Read(buff, 0, buffLength);
int allbye = (int)fileInf.Length;


int startbye = 0;
this.myProgressControl.Maximum = allbye;
this.myProgressControl.Minimum = 0;
this.myProgressControl.Visible = true;
this.lbl_ftpStakt.Visible = true;
this.lbl_ftpStakt.Text = "服务器连接中... ";
// 流内容没有结束
while (contentLen != 0)
{
// 把内容从file stream 写入 upload stream
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
startbye +=contentLen;
this.lbl_ftpStakt.Text = "已上传: "+(int)(startbye/1024) + "KB/ "+ "总长度: " + (int)(allbye/1024)+ "KB " + "/文件名: " +fileInf.Name;
myProgressControl.Value = startbye;
}
// 关闭两个流
strm.Close();
fs.Close();
this.myProgressControl.Visible = false;
this.lbl_ftpStakt.Text = "上传成功! ";
}


catch (Exception ex)
{
MessageBox.Show(ex.Message, "Upload Error ");
}
Interlocked.Decrement(ref flag);
mt.ReleaseMutex();
}


[解决办法]
学习
[解决办法]
将RunsOnWorkerThread方法放在一个新类中
该类要有一个保存filename的属性
这样才能保证每个线程的filename值不同

读书人网 >C#

热点推荐