Search code examples
c#form-load

i can´t run my app because i have a loop in my form_load |windows form application c#|


I have a problem in my hands. I have a program in which the client (form1) has to try to reconnect whenever it can not connect to the server. The loop that I have to do the reconnection is inside the Fomr_load so that the reconnection is automatic. But the problem is that the application does not open until form_load is complete. Who knows where I'm goin tell me please

 private void Form1_Load(object sender, EventArgs e)
    {
        Client = new TcpClient();
        IPEndPoint IP_End = new IPEndPoint(IPAddress.Parse("192.168.254.38"), 100);
        try
        {
            Socket Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            Client.Connect(IP_End);

            if (Client.Connected)
            {
                STW = new StreamWriter(Client.GetStream());
                STR = new StreamReader(Client.GetStream());
                STW.AutoFlush = true;

                backgroundWorker1.RunWorkerAsync();
                backgroundWorker1.WorkerSupportsCancellation = true;
            }
            else
            {
                reconnect();
            }
        }
        catch (SocketException)
        {
            reconnect();
        }
    }  



private void reconnect()
    {
        try
        {
            IPEndPoint IP_End = new IPEndPoint(IPAddress.Parse("192.168.254.38"), 100);
            Client.Connect(IP_End);
            STW = new StreamWriter(Client.GetStream());
            STR = new StreamReader(Client.GetStream());
            STW.AutoFlush = true;

            backgroundWorker1.RunWorkerAsync();
            backgroundWorker1.WorkerSupportsCancellation = true;
        }
        catch (SocketException)
        {
            reconnect();
        }
    }


private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {

        while (Client.Connected)
        {
            try
            {
                receive = STR.ReadLine();
                label1.Invoke(new MethodInvoker(delegate () { label1.Text = (receive + "\n\r"); }));
                receive = "";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }
    }

Solution

  • Have a boolean variable that you set to true once you connect successfully and then check that as well before calling reconnect(), so your loop should run once, set connectedSuccessfully = true, then next time it runs it will see that it's true and skip over the call to reconnect(). You probably also want to add a timer to maybe try once again after 1 second, then try again in 5 seconds, then again in 10 etc etc.