I would be great if someone could help me out.
In my application I'am trying to connect to a server using the try-catch-statement.
I would like to run a progress bar (or progress spinner) while the client is trying to connect to the server and to stop when the connection is established or failed. But it doesn't work.. Any ideas how to do this?
Here's my form code:
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 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;
}
}
}
Thanks!
Solved!
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;
}
}