使用Lock 将你使用的对象锁定起来
[C#] 纯文本查看 复制代码 private void ConnectFtp()
{
Monitor.Enter(this);
lock (listView1.Items) //此处为锁定listView1.Items,当次线程在访问时,其他线程处于等待状态,释放以后其他线程自动获得对该对象的访问权限
{
for (i = 0; i < listView1.Items.Count; i++)
{
try
{
FtpWebRequest req;
req = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + listView1.Items[i].SubItems[0].Text));
req.Credentials = new NetworkCredential(listView1.Items[i].SubItems[1].Text, listView1.Items[i].SubItems[2].Text);
req.KeepAlive = false;
req.Method = WebRequestMethods.Ftp.ListDirectory;
req.UseBinary = true;
WebResponse response = req.GetResponse();
response.Close();
listView1.Items[i].SubItems[3].Text = "登录成功";
}
catch (Exception)
{
listView1.Items[i].SubItems[3].Text = "登录失败";
}
}
}
Monitor.Exit(this);
}
|