我正在开发一个在串口读取RFID的应用程序。我使用timer
继续扫描,直到用户点击按钮。
当扫描仪找到新的RFID时,我将信息插入DataGridView
,如果RFID已经在DataGridView
我用绿色绘制行,并且DataGridView
中有RFID在扫描仪范围内我不再用白色绘画。
我的问题是,随着时间的推移,RFID不止一次插入。
我认为它是针对计时器中的线程的,所以我在内部设置了lock
,但是如果我尝试在小于200毫秒的时间内扫描,问题仍然存在。
有没有办法改进代码?
void tmrRepeatedScan_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
try
{
lock (thisLock)
{
var detectedTags = serialPort.Scan(true, false, true, false);
foreach (var tag in detectedTags)
{
bool tagFound = false;
string TID = Regex.Replace(Conversions.ByteToHexadecimal(tag.GetTagId()), "(.{2})(?!$)", "$0-");
string EPC = Regex.Replace(Conversions.ByteToHexadecimal(tag.GetEpc()), "(.{2})(?!$)", "$0-");
if (!tagsReaded.Contains(TID))
{
tagsReaded.Add(TID);
}
foreach (DataGridViewRow row in dgvTags.Rows)
{
if (row.Cells[0].Value.ToString().Equals(TID))
{
row.DefaultCellStyle.BackColor = Color.LightGreen;
tagFound = true;
break;
}
}
if (!tagFound)
{
dgvTags.BeginInvoke(new InvokeDelegate(() => AddRow(TID, EPC)));
}
}
}
foreach (DataGridViewRow row in dgvTags.Rows)
{
if (!tagsReaded.Contains(row.Cells[0].Value.ToString()))
{
row.DefaultCellStyle.BackColor = Color.White;
}
}
}
catch (Exception ex)
{
foreach (DataGridViewRow row in dgvTags.Rows)
{
row.DefaultCellStyle.BackColor = Color.White;
}
}
}
对不起,如果我的英语不是很好。
答案 0 :(得分:0)
您可以将其切换回string[] unwanted = new[] { "-","Mac", "Address", "Table", "Vlan", "Type", "Ports" };
var textList = text.Split(' ').ToList();
textList.RemoveAll(x => unwanted.Contains(x));
foreach(string line in textList)
{
if(!String.IsNullOrEmpty(line))
{
writeFile(line+",");
}
}
,但在执行BeginInvoke
之前,您需要检查tagsReaded
中的代码是否存在。试试这个:
AddRow