我设置了一个timer控件,每隔几秒钟 就向服务端尝试连接是否成功当连接成功的时候,我就让timer的enable为false,然后调用线程进行数据的接收timer控件的代码如下:
//client是我定义的一个TcpClient
           
 if (client==null) //当client为null的时候,就不断的尝试连接服务端
      {
            try
                {
                    client = new TcpClient(Dns.GetHostName(), 51888);
                }
            catch
                { 
                
                }
       }
  else
       {
                this.timer1.Enabled = false;
                connecto();
        }//connecto()如下代码:
   private void connecto()
        { 
            
            //获取网络流
              NetworkStream netStream = client.GetStream();
            sr = new StreamReader(netStream, System.Text.Encoding.UTF8);
            sw = new StreamWriter(netStream, System.Text.Encoding.UTF8);
            Thread myThread = new Thread(new ThreadStart(ReceiveData));
            myThread.Start();
        }//ReceiveData 代码如下: private void ReceiveData()
        {
         
         while (true)
            {
                string receiveString = null;
                try
                {
                    receiveString = sr.ReadLine();
                }
                catch
                {
                   MessageBox.Show("接收数据失败");
                }
                if (receiveString == null)
                {
                  MessageBox.Show("与服务器断开连接");
                  client.close();
                  client=null;
                   this.timer1.Enabled = true; //当与服务器断开连接的时候,我就要开启timer1控件,再次不断的进行尝试连接            
                   break;
                }
             
                MessageBox.Show("收到:" + receiveString);            }我觉得我的思路好像没有问题,就是当我的线程ReceiveData()检测到和服务端断开连接后,就让timer1.Enable=true;
让它再次不断的尝试连接服务端,但是我感到奇怪的是,timer.Enable=true;好像一点用都没有,那个timer控件也不会再次执行了,究竟是什么原因呢??哪位大哥说下,谢了!!

解决方案 »

  1.   

    这样跨线程访问控件不安全,需要用委托,这样的例子很多
    还有一种处理办法:不用timer控件,直接在需要启动timer的时候创建timer类对象
      

  2.   

    你看一下这几个博客
    不知是否有帮助
    http://www.builder.com.cn/2007/1104/604529.shtmlhttp://www.cnblogs.com/xugang/archive/2008/04/15/1154689.htmlhttp://www.cnblogs.com/hexiaosheng/archive/2008/04/14/1152311.html
      

  3.   

    现在我的做法是开了那个timer控件,不让他停下来,各位大哥,谁能给出代码的例子,给我学习学习