private void KeepAlivePLC() { while (true) { int x = -1; short arrayval = 0; taskint = Task.Factory.StartNew <int>(new Func <int>(() => { return(mxComponentCla.Read("M8000", out arrayval)); })); bool bol = taskint.Wait(new TimeSpan(0, 0, 0, 3)); if (!bol) { connectionStatus = false; this.Invoke(new Action(() => { label3.Text = "未连接"; label3.ForeColor = System.Drawing.Color.Red; })); if (startStopProduct) { startStopProduct = false; this.Invoke(new Action(() => { btn_conn.Enabled = true; })); MessageBox.Show("PLC请求超时,请检查PLC连接状态,重启客户端", " 武汉镭立科技友情提示", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { x = taskint.Result; if (x != 0) { connectionStatus = false; this.Invoke(new Action(() => { label3.Text = "未连接"; label3.ForeColor = System.Drawing.Color.Red; })); if (startStopProduct) { startStopProduct = false; this.Invoke(new Action(() => { btn_conn.Enabled = true; })); MessageBox.Show("PLC连接已断开,请检查PLC连接状态,重启客户端", " 武汉镭立科技友情提示", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } if (!connectionStatus) { if (mxComponentCla != null) { mxComponentCla.MxClose(); mxComponentCla = null; } mxComponentCla = new MxComponentCla(axActUtlType1, "9"); int m = mxComponentCla.MxOpen(); if (m == 0 && mxComponentCla.PlcSatte() == 1) { connectionStatus = true; this.Invoke(new Action(() => { label3.Text = "已连接"; label3.ForeColor = System.Drawing.Color.Green; })); } else { connectionStatus = false; this.Invoke(new Action(() => { label3.Text = "未连接"; label3.ForeColor = System.Drawing.Color.Red; })); } } Thread.Sleep(2000); } }
private void MxComponentConnFrm_Load(object sender, EventArgs e) { mxComponentCla = new MxComponentCla(axActUtlType1, "9"); mxComponentCla.MxOpen(); if (mxComponentCla.PlcSatte() == 1) { connectionStatus = true; label3.Text = "已连接"; label3.ForeColor = System.Drawing.Color.Green; } else { connectionStatus = false; label3.Text = "未连接"; label3.ForeColor = System.Drawing.Color.Red; } Task task = Task.Factory.StartNew(() => { KeepAlivePLC(); }); }
/// <summary> /// 连接 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button1_Click(object sender, EventArgs e) { if (button1.Text == "连接") { if (mxComponentCla == null) { mxComponentCla = new MxComponentCla(axActUtlType1, txtConNode.Text.Trim()); mxComponentCla.MxOpen(); DeviceStateTextEdit(label3, mxComponentCla.PlcSatte()); KeepAliveTime.Start(); } } else { if (mxComponentCla != null) { mxComponentCla.MxClose(); mxComponentCla = null; DeviceStateTextEdit(label3, 0); KeepAliveTime.Stop(); } } }