如何在try-catch-statement(通过tcp套接字连接到服务器时)运行进度条(Marquee)或进度微调器?

时间:2016-05-18 18:00:32

标签: tcp progress-bar try-catch tcpsocket

如果有人可以帮助我,我会很棒。

在我的应用程序中,我尝试使用try-catch-statement连接到服务器。

我想在客户端尝试连接到服务器时运行进度条(或进度微调器),并在连接建立或失败时停止。但它不起作用..任何想法如何做到这一点?

这是我的表单代码:

    private void btnConnect_Click(object sender, EventArgs e)
    {
        IPAddress ipAddress = null;
        ConnectionManager _conMngr = new ConnectionManager();

        if (IpAddress != String.Empty && IPAddress.TryParse(IpAddress, out ipAddress))
        {
            progressSpinner.Visible = true; // This is my progressSpinner
            lblStatus.Text = "Trying to connect...";

            try
            {
                _conMngr.ConnectToServer(IpAddress);
            }
            catch (SystemException ecp)
            {
                txtInfoBox.Text += Environment.NewLine + "Connection failed! " + ecp.Message;
            }   
        }
        else
            MessageBox.Show(this, "Please enter a valid IP address!", "Error: Invalid IP address", MessageBoxButtons.OK, MessageBoxIcon.Error);

ConnectionManager类:

public class ConnectionManager
{
    public Socket clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);

    public void ConnectToChargingStation(string ip)
    {
        try
        {
            IPEndPoint ipEnd = new IPEndPoint(IPAddress.Parse(ip), 13000);
            clientSock.Connect(ipEnd);
        }
        catch (Exception ex)
        {
            throw ex;
        }
     }
}

谢谢!

1 个答案:

答案 0 :(得分:0)

解决!

      private async void btnConnect_Click(object sender, EventArgs e) 
      { 
                progressSpinner.Visible = true;
                lblStatus.Text = "Status: Trying to connect...";
                pgbBusy.Visible = true;

                try
                {
                    await Task.Factory.StartNew(() =>
                    {
                        _conMngr.ConnectToServer(IpAddress);
                        lblStatus.Text = "Status: Connected to " + IpAddress;
                    });
                }
                catch (SystemException excp)
                {
                    InfoBoxText += Environment.NewLine + "Connection failed! " + excp.Message;
                    lblStatus.Text = "Status: Disconnected";
                }
                finally
                {
                    progressSpinner.Visible = false;
                    pgbBusy.Visible = false;
                } 
      }