//获取任务的线程 public void TaskThreadStart() { var devCommStateTimer = 0; var dt = new DataTable(); var sendTask = new Dictionary <int, int>(); var bll = new ESMonitor.BLL.Tasks(); while (_mThread.IsAlive) { var numOfDevs = _mList.Count; if (devCommStateTimer < _mCheckDevCommStateTime) { devCommStateTimer += _mThreadCycleTime; } else { DevsManage.ManageDevCommState(_mCheckDevCommStateTime); devCommStateTimer = 0; } if (numOfDevs > 0) { dt.Clear(); sendTask.Clear(); try { dt = bll.GetList("Status=0").Tables[0]; } catch (Exception) { continue; } for (var i = 0; i < dt.Rows.Count; i++) { if (!_mThread.IsAlive) { break; } try { var devId = Convert.ToInt32(dt.Rows[i]["DevId"]); //DevsManage.GetLocalCtrlAddr(localCtrlId, ref addr); if (sendTask.ContainsKey(devId)) { continue; } else { sendTask.Add(devId, 1); } if (devId > 0) { switch ((CommStatus)DevsManage.GetDevStatus(devId)) { case CommStatus.Busy: //发送时间超过最大等待时间,删除该发送任务;等下一个周期发送新的任务 if (DevsManage.IsCommTimeout(devId, _mWaittimeout)) { var taskId = DevsManage.GetCurTaskId(devId); bll.UpdateStatus(taskId, 2); //发送超时 //DevsManage.SetRecvMsgState(devId, false); DevsManage.SetCurTaskId(devId, 0); DevsManage.SetDevStatus(devId, (int)CommStatus.Free); //重新发送N次 //N次后依然不成功,就提示用户并保留不成功的日志 } break; //仅通信准备就绪,空闲时发送数据 case CommStatus.Free: if (DevsManage.IsRegistered(devId)) { var taskId = Convert.ToInt64(dt.Rows[i]["TaskId"]); var length = Convert.ToInt32(dt.Rows[i]["Length"]); var buffer = (byte[])(dt.Rows[i]["Data"]); var protocol = Element(devId); //根据id取协议 if (protocol.AsyncSocketUserToken.ConnectSocket != null) { lock (protocol) { if (protocol.DoSendResult(buffer, 0, length)) //true表示发送成功 { DevsManage.SetCurTaskId(devId, taskId); DevsManage.SetDevStatus(devId, (int)CommStatus.Busy); DevsManage.UpdateSendTime(devId); } } } } break; //通信状态断开,不发送 case CommStatus.DisConnect: break; } } } catch (Exception e) { Program.Logger.ErrorFormat("Task thread send command error, message: {0}", e.Message); Program.Logger.Error(e.StackTrace); Program.OutputLog.LogFormat("Task thread send command error, message: {0}", e.Message); } } } if (!_mThread.IsAlive) { break; } Thread.Sleep(_mThreadCycleTime); //每秒钟 } dt.Clear(); }