我对编程还很陌生,并且不确定我是否以正确的方式进行操作。
我已经在主窗体上创建了一个按钮,该按钮调用一个单独的类并将返回值附加到richtextbox。另一个类对计算机执行ping操作,并(显然)返回我想要的文本。
---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;
} } }
我的代码的主要问题是,while循环以主形式无限运行(它确实正确地附加了文本),但是冻结了程序(我希望能够再次按下按钮并停止while循环) -我意识到我尚未编写逻辑来停止while循环,因为它会立即冻结程序,因此我需要解决第一个问题。我也不知道最好的方法。
是否有更好的方法在类中运行while循环,而不是返回字符串,而是将文本实际附加到类中的richtextbox1中(甚至可能吗?)现在,它一遍又一遍地调用函数,对我来说,这似乎是错误的。
还是我这样做正确,但是需要以某种方式将函数调用分成不同的进程? (我不知道如何)。
答案 0 :(得分:0)
您必须使用async和await在另一个线程中运行循环-> https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/
对于您的标签,您可以尝试--How do I update the GUI from another thread?
希望有帮助