/// <summary> /// 同一PLC不同DB块同时读取数据 /// </summary> /// <param name="pLCAddrLists"></param> /// <returns><eturns> public int AsyncMultiDBStart() { _hda = new List <HistoryData>(); List <PLCAddrList> pLCAddrLists = GetPLCAddrLists(_Addr); CancellationToken token = tokenSource.Token; _dataTyte = comm.DataTyte.STRING; _PLCDriver.IP = this._IP; _PLCDriver.Connect(); if (IsConnect) { isFirst = false; Result = "与PLC连接成功:" + _IP + "地址为" + _Addr + "---------" + DateTime.Now + "\r\n"; } else { Result = "与PLC连接失败:" + _IP + "地址为" + _Addr + "---------" + DateTime.Now + "\r\n"; } Task task = new Task(() => { while (true) { try { string send = null; string recive = null; bool check = true; double during = 0; int length = 0; string DBAddr = null; foreach (var item in pLCAddrLists) { if (token.IsCancellationRequested) { _hda.Clear(); _PLCDriver.Dispose(); throw new OperationCanceledException(token); } send = GetRandomString(item.DataLenth * 2); _PLCDriver.Address = item.Addr; int ret = _PLCDriver.WriteBytes(SoftBasic.HexStringToBytes(send)); if (ret != 0) { string result = item.Addr + "写数据失败:" + _PLCDriver.ErrorCode + "---------" + DateTime.Now + "\r\n"; if (MessageEventHandler != null) { MessageEventHandler(result, null); } } ret = _PLCDriver.ReadBytesResult(item.DataLenth); if (ret != 0) { string result = _IP + item.Addr + "读数据失败:" + _PLCDriver.ErrorCode + "---------" + DateTime.Now + "\r\n"; if (MessageEventHandler != null) { MessageEventHandler(result, null); } } byte[] ReciveData = _PLCDriver.ReadBuff as byte[]; recive = SoftBasic.ByteToHexString(ReciveData); during += (_PLCDriver.Readtime - _PLCDriver.Sendtime).TotalMilliseconds; check &= send.Equals(recive); DBAddr += item.Addr; length += item.DataLenth; } _hda.Add(new HistoryData(during, length, check, DateTime.Now, DBAddr)); // UpdateUIDelegate(LogMessage); if (ListData.Count > 10) { switch (DataTyte) { case comm.DataTyte.BOOL: break; case comm.DataTyte.WORD: SaveData <HistoryData>("HistoryData_Word" + ThreadCount, ListData); break; case comm.DataTyte.INT16: SaveData <HistoryData>("HistoryData_Int16" + ThreadCount, ListData); break; case comm.DataTyte.INT32: SaveData <HistoryData>("HistoryData_Int32" + ThreadCount, ListData); break; case comm.DataTyte.REAL: SaveData <HistoryData>("HistoryData_real" + ThreadCount, ListData); break; case comm.DataTyte.STRING: SaveData <HistoryData>("HistoryData_str" + ThreadCount, ListData); break; default: break; } } } catch (Exception ex) { if (MessageEventHandler != null) { MessageEventHandler(_PLCDriver.ErrorCode + ex.Message.ToString(), null); } if (token.IsCancellationRequested) { break; } } } }, token); task.Start(); return(0); }