读书人

C#多线程扫描在程序结束处出现错误!

发布时间: 2012-03-11 18:15:38 作者: rapoo

C#多线程扫描,在程序结束处出现异常!异常提示是“如何跨线程调用Windows窗体”!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;

namespace WindowsApplication2
{
public partial class Form1 : Form
{
Thread[] thread;
public Form1()
{
InitializeComponent();
thread = new Thread[1];
for (int i = 0; i < 1; i++)//利用循环初始化10个线程
{
Thread t = new Thread(new ThreadStart(scan));
thread[i] = t;
}
}

private void Form1_Load(object sender, EventArgs e)
{

}


int a, b, c, d;
string ipString;


private void button1_Click(object sender, EventArgs e)
{


for (int i = 0; i < 1; i++)
{

thread[i].Start();
}


}

public bool isPortOpen(string ip)
{
try


{
TcpClient client = new TcpClient();//创建一个TcpClient实例
IPAddress address = IPAddress.Parse(ip);//转化string类型的IP地址到IPAddress
client.Connect(address, 7458);//连接服务器address的port端口
client.Close();//连接成功立即断开

return true;//返回true,连接成功
}
catch//连接失败TcpClient类抛出异常,这里捕获
{

return false;//返回false,连接失败
}
}


public void scan()
{
for(a=192;a <=192;a++)
{
for(b=168;b <=168;b++)
{
for(c=0;c <=0;c++)
{

for(d=1;d <=255;)
{
string ss;
lock (this)


{
ipString = a.ToString().Trim() + ". " + b.ToString().Trim() + ". " + c.ToString().Trim() + ". " + d.ToString().Trim();
ss=ipString;
d++;
}
if(this.isPortOpen(ss))
listBox1.Items.Add((object)(ip + "\n "));

else
this.listBox2.Items.Add((object)(ip + "\n "));

}
}
}


}





}
}



}

[解决办法]
listBox1.Items.Add((object)(ip + "\n "));


=========================

delegate void EmptyDelegate();
EmptyDelegate d = delegate
{
listBox1.Items.Add((object)(ip + "\n "));
};
this.Invoke(d);
[解决办法]
参考一下这个
private delegate void DelUpdateText(string text);

private void UpdateText(string text)
{
if(this.InvokeRequired)
{
this.Invoke(new DelUpdateText(UpdateText), new object[]{text});
}
else
{
yourTextBox.Text = text;
}
}

读书人网 >C#

热点推荐