我在main_form中声明了一个socket套接字client
public socket client;
private void button1_Click(object sender, EventArgs e)
{
thread mythread = new thread(new threadstart(Listen));
mythread.start();
}
void Listen()
{
try
{
client = new socket();
client.connect(remoteIP,port);
this.hide();
form2 f2 = new form2(client);//连接成功时显示form2窗体
f2.show();
}
catch
{
}
}
请问这样写可以么?如果不可以的话,我应该怎么样才能让client非空(有连接时)才显示form2窗体?
public socket client;
private void button1_Click(object sender, EventArgs e)
{
thread mythread = new thread(new threadstart(Listen));
mythread.start();
}
void Listen()
{
try
{
client = new socket();
client.connect(remoteIP,port);
this.hide();
form2 f2 = new form2(client);//连接成功时显示form2窗体
f2.show();
}
catch
{
}
}
请问这样写可以么?如果不可以的话,我应该怎么样才能让client非空(有连接时)才显示form2窗体?
Thread mythread = new Thread(new ThreadStart(Listen));
mythread.Start();
}
delegate void D();
void Listen() {
D d = new D(() => { Form2 f2 = new Form2(); f2.Show(); });
this.Invoke(d);
}
while{true}
{
if(client! = null)
{
form2 f2 = new form2(client);
form2.show();
break;
}
}
可是这样还是不行
原则上不能在线程中操作UI控件或窗体的,参考2楼的方法吧,用Invoke
private void button1_Click(object sender, EventArgs e) {
Thread mythread = new Thread(new ThreadStart(Listen));
mythread.Start();
}
delegate void D(Socket s);
void Listen() {
Socket s=new Socket();
...
D d = new D(() => { Form2 f2 = new Form2(); f2.Show(); });
this.Invoke(d, s);
}