-1

I am fairly new to programming, and am not sure I'm doing this the correct way.

I've created a button on my main form that calls a separate class and appends the return to a richtextbox. This other class pings a machine and returns the text I want (obviously).

   ---Here is the main form and the button within it--


    public void Btn_Ping_Click_1(object sender, EventArgs e)
    {
        Class1 pingClass = new Class1();

        if (Btn_Ping.Text == "Ping")
        {
            Btn_Ping.Text = "Stop Ping";
        }
        else if (Btn_Ping.Text == "Stop Ping")
        {
            Btn_Ping.Text = "Ping";
        }
        while (Btn_Ping.Text == "Stop Ping")
        {
            richTextBox1.AppendText(pingClass.PingHost(Txt_Main.Text));
        }
    }



 ---Here is the seperate class that pings the machine and returns text--



namespace HelpDeskTools.Service.Classes
{
   class Class1
{
    HelpdeskTools_MainInterface mainForm = new HelpdeskTools_MainInterface();

    public string PingHost(string host)
    {
        //string to hold our return messge
        string returnMessage = string.Empty;

        //IPAddress instance for holding the returned host
        var address = Dns.GetHostEntry(host).AddressList.First();

        //set the ping options, TTL 128
        PingOptions pingOptions = new PingOptions(128, true);

        //create a new ping instance
        Ping ping = new Ping();

        //32 byte buffer (create empty)
        byte[] buffer = new byte[32];

        var HasConnection = NetworkInterface.GetIsNetworkAvailable();

        //first make sure we actually have an internet connection
        if (HasConnection)
        {

                try
                {
                    //send the ping 4 times to the host and record the returned data.
                    //The Send() method expects 3 items:
                    //1) The IPAddress we are pinging
                    //2) The timeout value
                    //3) A buffer (our byte array)
                    PingReply pingReply = ping.Send(address, 1000, buffer, pingOptions);

                    //make sure we dont have a null reply
                    if (!(pingReply == null))
                    {
                        switch (pingReply.Status)
                        {
                            case IPStatus.Success:
                                returnMessage = string.Format("Reply from host: bytes={0} Response Time={1}ms ", pingReply.Buffer.Length, pingReply.RoundtripTime);
                                break;
                            case IPStatus.TimedOut:
                                returnMessage = "Connection has timed out...";
                                break;
                            default:
                                returnMessage = string.Format("Ping failed: {0}", pingReply.Status.ToString());
                                break;
                        }
                    }
                    else
                        returnMessage = "Connection failed for an unknown reason...";
                }
                catch (PingException ex)
                {
                    returnMessage = string.Format("Connection Error: {0}", ex.Message);
                }
                catch (SocketException ex)
                {
                    returnMessage = string.Format("Connection Error: {0}", ex.Message);
                }

        }
        else
            returnMessage = "No Internet connection found...";

        //return the message
        return returnMessage;
    } } }

The main problem with my code, is that the while loop runs in the main form infinitely (it does correctly append the text) but freezes the program (I want to be able to press the button again and stop the while loop) - I realize I didnt code the logic to stop the while loop in yet, because it freezes the program instantly and I need to address that first anwyay. I also dont know the best way to do this.

Is there a better way to run the while loop in the class and instead of returning a string, and actually append the text to the richtextbox1 WITHIN the class (is that even possible?) Right now its calling the function over and over, and to me that seems wrong.

Or am I doing this the right way but need to separate the function call into a different process somehow? (I have no idea how).

William
  • 23
  • 4

1 Answers1

0

You must run your loop in another thread with async and await -> https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/

And for your label you can try this -> How do I update the GUI from another thread?

Hope it helps

Greenkiller
  • 200
  • 2
  • 12