[英]Code lags UI but I am unclear how to use Background worker on a task that requires inputs
I am pinging about 10-15 ips on my network (employee phones) to put up a display if they are in the office our out of the office 我要在网络上(员工电话)ping大约10-15 ips来摆放显示器,如果他们在办公室我们不在办公室
I have a timer that has a 5000ms tick that kicks of a ping on all the ip's 我有一个计时器,它具有一个5000ms的滴答声,可在所有IP上执行ping操作
I've tried to do a background worker or a tread but the problem is that they seem to either 1) not want to take passed paramiters or 2) do not have access to update form controls 我尝试做后台工作人员或脚踏车,但问题是他们似乎要么1)不想采用已通过的参数,要么2)无法访问更新表单控件
private void Check()
{
foreach (StatusBox sb in flowLayoutPanel1.Controls)
{
Ping pingSender = new Ping();
PingReply reply = pingSender.Send(sb.IPaddress, 10);
if (reply.Status == IPStatus.Success) //device found update last seen
{
sb.Color = Color.Green;
sb.lastseen = DateTime.Now.ToLongTimeString();
sb.lastseenDate = DateTime.Now;
}
else
{
if (sb.lastseenDate != Convert.ToDateTime("1/1/0001 12:00:00 AM")) //no date means device has not been found yet
{
if (sb.lastseenDate.AddMinutes(10) < DateTime.Now)
{
sb.Color = Color.Yellow;
}
else if (sb.lastseenDate.AddHours(1) < DateTime.Now)
{
sb.Color = Color.LightGray;
}
}
}
}
Accessing controls on a form is not thread safe, to change properties to a control you need to access the control from the thread the window form is running... For example here a function to change the color of your Status box 访问表单上的控件不是线程安全的,要更改控件的属性,您需要从运行窗口表单的线程访问该控件。例如,此处有一个用于更改状态框颜色的函数
private void SetColor(StatusBox sb, Color col)
{
if (sb.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetColor);
this.Invoke(d, new object[] { col});
}
else
{
sb.Color = col;
}
}
You can find more examples and explainations on this page : https://msdn.microsoft.com/en-us/library/ms171728(v=vs.110).aspx 您可以在此页面上找到更多示例和解释: https : //msdn.microsoft.com/zh-cn/library/ms171728(v= vs.110).aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.