我是一个编程新手,我试图做我的第一件事,这将是为别人而不仅仅是我(所以不应该是那种蹩脚的^^)C#方法中带参数的线程使用相同的变量
这是局域网内客户端的在线检查器(所以他可以粘贴客户端列表,并返回在线或离线状态)。
fyi:我正在使用Try/Catch,因为ping.send到脱机主机返回的错误导致应用程序崩溃。
目前,它看起来像这样:
private void btn_check_Click(object sender, EventArgs e)
{
string[] hosts = txt_hosts.Text.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
foreach (String host in hosts)
{
pinger(host);
}
}
public void pinger(string host)
{
var ping = new System.Net.NetworkInformation.Ping();
try
{
var result = ping.Send(host);
txt_result.Text += "true" + Environment.NewLine;
Application.DoEvents();
}
catch
{
txt_result.Text += "false"+Environment.NewLine;
Application.DoEvents();
}
}
现在,界面中,就像冰冻每当ping.send正在处理(这就是ping命令的超时的幽长的原因)。
有没有办法做到这一点?在我尝试启动一个线程之前,但这不起作用,因为都写入txt_result并返回一个错误。
感谢您的帮助!
,因为你做的UI(我想你说的接口)被冻结什么所谓的“阻塞操作” - 你在GUI线程中运行代码,并要运行它在正常线程上。您需要从工作线程调用ping。阅读http://msdn.microsoft.com/en-us/library/system.threading.threadpool.queueuserworkitem.aspx Synrhconize你的线程和写入外部文件。 – ilansch
对于使用Application.DoEvents()的相同 –
不好的练习,您也可以使用BackgroundWorker。不惜一切代价避免它。此外你的catch块是空的(即没有捕获正确或特定的异常来适当地处理错误)。为什么? –