如果重复此消息,可能会有人提供如何忽略消息的最佳方法,我应该使用什么来忽略,保存列表中的消息并遍历列表或将所有消息保存到文件中,最好的方法是什么?我使用以下代码从串口读取数据:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO.Ports;
namespace canSniff
{
class PortDataReceived
{
public static void Main()
{
SerialPort mySerialPort = new SerialPort("COM4");
mySerialPort.BaudRate = 115200;
mySerialPort.Parity = Parity.None;
mySerialPort.StopBits = StopBits.One;
mySerialPort.DataBits = 8;
mySerialPort.Handshake = Handshake.None;
mySerialPort.RtsEnable = true;
mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
mySerialPort.Open();
Console.WriteLine("Press any key to continue...");
Console.WriteLine();
Console.ReadKey();
}
private static void DataReceivedHandler(
object sender,
SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string indata = sp.ReadExisting();
Console.WriteLine("Data Received:");
Console.Write(indata);
}
}
}
答案 0 :(得分:1)
您可以使用HashSet<string>
存储收到的邮件。
如果您将其另存为文件,则取决于应用程序的使用方式。下面的代码知道应用程序运行所收到的消息的时间。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO.Ports;
namespace canSniff
{
class PortDataReceived
{
private HashSet<string> _messages = new HashSet<string>();
public static void Main()
{
SerialPort mySerialPort = new SerialPort("COM4");
mySerialPort.BaudRate = 115200;
mySerialPort.Parity = Parity.None;
mySerialPort.StopBits = StopBits.One;
mySerialPort.DataBits = 8;
mySerialPort.Handshake = Handshake.None;
mySerialPort.RtsEnable = true;
mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
mySerialPort.Open();
Console.WriteLine("Press any key to continue...");
Console.WriteLine();
Console.ReadKey();
}
private static void DataReceivedHandler(
object sender,
SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string indata = sp.ReadExisting();
if(_messages.Add(indata))
{
// the message was added
Console.WriteLine("Data Received:");
Console.Write(indata);
}
else
{
// do something with the omitted message that was allready in the list
}
}
}
}