我在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窗体?

解决方案 »

  1.   

    client.connect(remoteIP,port);这个后 判断 client.connected,如果 is true 就直接show form2
      

  2.   

    你的代码中form2不是跑在主线程的,而是泡在你的子线程上这样当你的子线程干完活退出之后,form2也就嗝屁了所以你的代码不对可以这样        private void button1_Click(object sender, EventArgs e) {
                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);
            }
      

  3.   

    我也想过这个,我在button1_click事件中的最后写入了
    while{true}
    {
        if(client! = null)
          {
              form2 f2 = new form2(client);
              form2.show();
              break;
           }
    }
    可是这样还是不行
      

  4.   


    原则上不能在线程中操作UI控件或窗体的,参考2楼的方法吧,用Invoke
      

  5.   

    可问题是我还要把主窗体中的client值传给子窗体啊(用构造函数),这样怎么用委托实现呢?求大侠指点,不胜感激!
      

  6.   


            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);
            }