本人最近学习C#Modbus通讯,要一直读取从站数据,但是在写的时候会和读冲突,导致线程阻塞,网上搜的要加读写锁,麻烦哪位指导一下
这里的读写锁应该怎么加,才能让读写不冲突
#region 读取输出线圈0x01
//Rx:01 01 00 00 00 0A BC 0D
//Tx:01 01 02 25 01 62 AC
/// <summary>
/// 读取输出线圈0x01
/// </summary>
/// <param name="slaveAddress">从站地址</param>
/// <param name="startAddress">起始地址</param>
/// <param name="count">读取数据数量</param>
/// <returns>布尔数组(若返回结果为null,则读取数据失败,若返回结果不为null,则数据读取成功)</returns>
public bool[] ReadOutPutCoil(byte slaveAddress, ushort startAddress, ushort count)
{
//1、拼接报文
List<byte> SendCommand = new List<byte>();
SendCommand.Add(slaveAddress);
SendCommand.Add(0x01);
SendCommand.Add((byte)(startAddress / 256));
SendCommand.Add((byte)(startAddress % 256));
SendCommand.Add((byte)(count / 256));
SendCommand.Add((byte)(count % 256));
SendCommand.AddRange(CRC16(SendCommand.ToArray()));
//2、发送报文
CurrentCOM.Write(SendCommand.ToArray(), 0, SendCommand.Count);
//3、接收报文
Thread.Sleep(100);
byte[] buffer = new byte[CurrentCOM.BytesToRead];
CurrentCOM.Read(buffer, 0, buffer.Length);
//4、验证报文
if (buffer.Length == (5 + (count <= 8 ? 1 : (count / 8 + 1))))
{
if (buffer[0] == slaveAddress && buffer[1] == 0x01 && buffer[2] == (count <= 8 ? 1 : (count / 8 + 1)))
{
//5、解析报文
byte[] result = new byte[count <= 8 ? 1 : (count / 8 + 1)];
//截取数据
Array.Copy(buffer, 3, result, 0, count <= 8 ? 1 : (count / 8 + 1));
return ByteArrToBoolArr(result);
}
}
return null;
}
#endregion
#region 读取输入线圈0x02
//Rx:01 02 00 00 00 0A F8 0D
//Tx:01 02 02 00 00 B9 B8
/// <summary>
/// 读取输入线圈0x02
/// </summary>
/// <param name="slaveAddress">从站地址</param>
/// <param name="startAddress">起始地址</param>
/// <param name="count">读取数据数量</param>
/// <returns>布尔数组(若返回结果为null,则读取数据失败,若返回结果不为null,则数据读取成功)</returns>
public bool[] ReadInPutCoil(byte slaveAddress, ushort startAddress, ushort count)
{
//1、拼接报文
List<byte> SendCommand = new List<byte>();
SendCommand.Add(slaveAddress);
SendCommand.Add(0x02);
SendCommand.Add((byte)(startAddress / 256));
SendCommand.Add((byte)(startAddress % 256));
SendCommand.Add((byte)(count / 256));
SendCommand.Add((byte)(count % 256));
SendCommand.AddRange(CRC16(SendCommand.ToArray()));
//2、发送报文
CurrentCOM.Write(SendCommand.ToArray(), 0, SendCommand.Count);
//3、接收报文
Thread.Sleep(100);
byte[] buffer = new byte[CurrentCOM.BytesToRead];
CurrentCOM.Read(buffer, 0, buffer.Length);
//4、验证报文
if (buffer.Length == (5 + (count <= 8 ? 1 : (count / 8 + 1))))
{
if (buffer[0] == slaveAddress && buffer[1] == 0x02 && buffer[2] == (count <= 8 ? 1 : (count / 8 + 1)))
{
//5、解析报文
byte[] result = new byte[count <= 8 ? 1 : (count / 8 + 1)];
Array.Copy(buffer, 3, result, 0, count <= 8 ? 1 : (count / 8 + 1));
return ByteArrToBoolArr(result);
}
}
return null;
}
#endregion