System.InvalidOperationException: 对象当前正在其他地方使用。 求大神帮忙看下代码。。。
做一个小托盘,通过telnet显示各个服务器端口状态,我是读取配置文件 动态加载显示控件的,
但是调试的时候一直出现标题提示的这个错误。有些时候能成功。。。。
小弟刚接触winform,求大神帮忙看下代码。
错误提示如下:
private void tray_Init()
{
Ping pg = new Ping();
TelnetClient tc = new TelnetClient();
int num = Convert.ToInt32(ConfigurationSettings.AppSettings["IPAndPortNum"]);
//lock (obj)
//{
int num0 = 0;
int num1 = 0;
for (int i = 0; i < num; i++)
{
string sectionid = "IPAndPort" + i.ToString();
string sectioninfo = ConfigurationSettings.AppSettings[sectionid];
string[] sArray = sectioninfo.Split('#');
string sectionname = sArray[0].ToString();
string sectionIP = sArray[1].ToString();
string sectionPort = sArray[2].ToString();
string sectiontype = sArray[3].ToString();
string imgpathok = Environment.CurrentDirectory.Replace("\\bin\\Debug", "") + "\\img\\blue.jpg";
string imgpathnotok = Environment.CurrentDirectory.Replace("\\bin\\Debug", "") + "\\img\\icon.ico";
PingReply pr = pg.Send(sectionIP);
switch (sectiontype)
{
case "0":
Label lblcontrol = (Label)flp.Controls[2 * i];
PictureBox pbcontrol = (PictureBox)flp.Controls[2 * i + 1];
//Telnet p = new Telnet(sectionIP, Convert.ToInt32(sectionPort), 8);
////判断是否Telnet成功,成功判断Ping-time。
//if (p.Connect() == false)
//{
// //lblResult.Text += "失败";
//}
//else
//{
//lblResult.Text = pr.ToString();
if (pr.RoundtripTime < 100)
{
pbcontrol.Load(imgpathok);
}
else
{
pbcontrol.Load(imgpathnotok);
}
num0++;
//}
//}
break;
case "1":
Label lblcontrol1 = (Label)flp1.Controls[2 * (i - num0)];
PictureBox pbcontrol1 = (PictureBox)flp1.Controls[2 * (i - num0) + 1];
//Telnet p = new Telnet(sectionIP, Convert.ToInt32(sectionPort), 8);
////判断是否Telnet成功,成功判断Ping-time。
//if (p.Connect() == false)
//{
// //lblResult.Text += "失败";
//}
//else
//{
//lblResult.Text = pr.ToString();
if (pr.RoundtripTime < 100)
{
pbcontrol1.Load(imgpathok);
}
else
{
pbcontrol1.Load(imgpathnotok);
}
num1++;
//}
//}
break;
case "2":
Label lblcontrol2 = (Label)flp2.Controls[2 * (i - num0 - num1)];
PictureBox pbcontrol2 = (PictureBox)flp2.Controls[2 * (i - num0 - num1) + 1];
//Telnet p = new Telnet(sectionIP, Convert.ToInt32(sectionPort), 8);
////判断是否Telnet成功,成功判断Ping-time。
//if (p.Connect() == false)
//{
// //lblResult.Text += "失败";
//}
//else
//{
//lblResult.Text = pr.ToString();
if (pr.RoundtripTime < 100 && pr.RoundtripTime > 0)
{
pbcontrol2.Load(imgpathok);
}
else
{
pbcontrol2.Load(imgpathnotok);
}
//}
//}
break;
}
[解决办法]
tray_Init 你这个方法是直接winform主线程里面跑的还是新启动一个线程来运行的?