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

How to run progress bar (Marquee) or progress spinner while try-catch-statement (while Connecting to server over tcp socket)?

如果有人能帮助我,我会很高兴。

在我的应用程序中,我正在尝试使用 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);

连接管理器Class:

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

谢谢!

已解决!

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