First of all: the ReadTimeout property should be setted once, i prefer just befor the opening action.
over the internet is full of snippet you could read, msdn has its own official way to read Serial Port, even if it ain't aiming to performance...
You should consider that the DataReceived event can be triggered every byte transferred so
avoid to put a polling cycle in that method.
instead use a global variable (byte[] or string) for the main buffer, then in the dataReceived you add till the data reach your expected value.
public event EventHandler<SerialEventArgs> SerialEvent;
public virtual void OnSerialEvent(SerialEventArgs e)
{
EventHandler<SerialEventArgs> handler = SerialEvent;
if (handler != null)
{
handler(this, e);
}
}
public class SerialEventArgs : EventArgs
{
private String evento;
public String Evento { get { return evento; } }
public SerialEventArgs(String e)
{
this.evento = e;
}
}
public void Ricevi(object sender, SerialDataReceivedEventArgs e)
{
buffer += serial.ReadExisting();
if (buffer.Contains("\r\n"))
{
OnSerialEvent(new SerialEventArgs(buffer));
buffer = "";
}
}
Beware of chunked data: there is no guarantee that the string ends with "\r\n" with ReadExisting, meanwhile the in the ReadLine method read till this special character(when they are, otherwise... bleee)
with this Event you can leave the entire management of the SerialPort object behind the scene and in your Form subscribe the custom event in here.
Hope this helps. Cheers!!