2016-05-18 17 views
0

Ich wäre großartig, wenn mir jemand helfen könnte.Wie Fortschrittsbalken (Marquee) oder Progress Spinner während Try-Catch-Anweisung (beim Verbinden mit dem Server über TCP-Socket) ausführen?

In meiner Anwendung versuche ich eine Verbindung zu einem Server herzustellen, indem ich die try-catch-Anweisung verwende.

Ich möchte eine Fortschrittsanzeige (oder Progress Spinner) ausführen, während der Client versucht, eine Verbindung mit dem Server herzustellen und zu stoppen, wenn die Verbindung hergestellt oder fehlgeschlagen ist. Aber es funktioniert nicht .. Irgendwelche Ideen, wie man das macht?

Hier ist meine 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-Klasse:

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

Dank!

Antwort

0

Gelöst!

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