我不能 运行 我的应用程序,因为我的 form_load |windows 表单应用程序 c#| 中有一个循环

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

我手上有问题。 我有一个程序,客户端 (form1) 在无法连接到服务器时必须尝试重新连接。 我必须执行重新连接的循环位于 Fomr_load 内,以便重新连接是自动的。 但问题是应用程序在 form_load 完成之前不会打开。 谁知道我要去哪里请告诉我

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

有一个布尔变量,一旦连接成功就设置为 true,然后在调用 reconnect() 之前也检查它,所以你的循环应该 运行 一次,设置 connectedSuccessfully = true,然后下次它运行s 它会发现它是真的并跳过对 reconnect() 的调用。您可能还想添加一个计时器,以便在 1 秒后重试,然后在 5 秒后重试,然后在 10 秒后重试,依此类推。