Lukáš Linhart
Lukáš Linhart

Reputation: 63

TcpClient Connect delay

I'm lost. When i want to edit something in my Form1 then i must after edit do command Form1.show(); So i don't edit open form but some invisible new form. I think it is somewhere in constructor, but i don't know where. Please help

Cli class:

    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 class:

    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Š"; }



    }...

Upvotes: 0

Views: 507

Answers (1)

CharithJ
CharithJ

Reputation: 47510

There is no infinite loop, I think you are experiencing a delay because it's waiting till TcpClient.Connect() returns.

Try async connect instead.

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

Upvotes: 1

Related Questions