First read the documentation on the library you are using - can the event be raised asynchronously? If not then you are done.
UPDATE: Apparently this particular event cannot be raised concurrently, see Hans Passant's answer.
If it can, one strategy is to use a lock
:
object myLock = new object();
void IBSerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
lock(myLock)
{
while (BytesToRead > 0)
{
ProcessByte((byte)ReadByte());
}
}
}
Take care now that you are using locks, if you lock on the same instance elsewhere you can get dead locks or if you hold the same lock for a while you will hold up processing...
Aside: generally the documentation will tell you if the event can raised concurrently so you will have to deal with re-entry, e.g. System.Threading.Timer
's Tick event, though this is not always the case, e.g. the serverly lacking WinRT documentation on DatagramSocket
's MessageReceived event.