2015-08-03 86 views
0

我迷路了。当我想编辑Form1中的某些东西时,我必须在编辑后执行Form1.show();所以我不编辑开放表格,但一些看不见的新形式。我认为这是建设者的某个地方,但我不知道在哪里。 请帮助TcpClient连接延迟

CLI的类:

public class Cli 
{ 
    Form1 frm; 
    TcpClient tcpclnt = new TcpClient(); 

    public Cli() 
    { 


    } 
    public void Connect() 
    { 
     frm = new Form1(); 
     try 
     { 

      frm.debug.Text = "Connecting"; 

      tcpclnt.Connect("127.0.0.1", 8001); 
      // use the ipaddress as in the server program 
      frm.debug.Text = "Connected"; 

     } 
     catch (Exception e) 
     { 
      frm.debug.Text=("Error..... " + e.StackTrace); 
      frm.Show(); 
     }... 

Form1类:

public partial class Form1 : Form 
{ 
    Cli client; 
    public int pocet = 0; 
    public Form1() 
    { 
     InitializeComponent(); 
     client =new Cli(); 
     Random rnd = new Random(); 

     pocet = rnd.Next(23, 10000); 
     if (pocet % 2 == 1) 
     { 
      label1.Text = "HRAJEŠ"; 
     } 
     else { label2.Text = "HRAJEŠ"; } 



    }... 
+1

正如下面的答案tcpclnt.Connect(“127.0.0.1”,8001);导致错误,除了创造一个新的胜利形式是不好的做法。分解视图和业务逻辑层 –

回答

1

没有无限循环,我觉得您遇到的延迟,因为它是等到TcpClient.Connect()回报。

尝试使用异步连接。

frm.debug.Text = "Connecting"; 

var client = new TcpClient(); 
var result = client.BeginConnect("127.0.0.1", 8001, null, null); 

var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(1)); 

if (!success) 
{ 
    throw new Exception("Failed to connect."); 
} 

// we have connected 

frm.debug.Text = "Connected"; 
client.EndConnect(result);