我正在尝试使用lock同时读取和写入列表。我通过在锁的帮助下从相同的列表中读取来处理这些字节,从串口添加字节到列表。我的问题是,在调试模式下运行它时工作正常,但正常运行时显示异常。以下是我的代码。
private void receiveData(object sender, SerialDataReceivedEventArgs e)
{
while (connectComPort.BytesToRead > 0)
receivedBytes1.Add((byte)connectComPort.ReadByte());
}
int tint = 0;
private static readonly object _object = new object();
private void modprocessReceivedBuffer()
{
while (1 == 1)
{
try
{
if (receivedBytes1.Count() > tint)
{
List<byte> receivedBytes12 = null;
lock (_object)
{
receivedBytes12 = receivedBytes1.GetRange(tint, 2).ToList<byte>(); //LINE 1
}
if (receivedBytes12[0] == 0x0D)
{
if (receivedBytes12[1] == 0xAF)
{
try
{
var tiff = receivedBytes1.GetRange(tint, ((int)receivedBytes1[tint + 4])).ToList<byte>();
tint += (int)receivedBytes1[tint + 4];
modifiedProcess(tiff);
if (receivedBytes1.Count() == tint)
{
receivedBytes1.Clear();
tint = 0;
Thread.Sleep(20);
}
}
catch
{
}
}
}
else
{
tint += 1;
}
}
}
catch (Exception ex)
{
Log.Error("bug : " + ex.ToString());
}
}
}
第1行显示&#34; System.ArgumentException:偏移量和长度超出数组的范围,或者计数大于从索引到源集合末尾的元素数量&#34;正常运行代码时。在调试模式下运行时,我无法捕获此错误。我的第二个问题是,如果他们是任何线程安全列表,如c#中的结构? 我还想补充一点,我从端口以非常快的速率16000字节/秒的平均速度接收数据。