- 
                Notifications
    
You must be signed in to change notification settings  - Fork 5.2k
 
Description
Description
.NET may raise NullReferenceException if the handler of the event SerialPort.DataReceived unsubscribes from this event.
The problem is in System.IO.Ports.SerialStream. EventLoopRunner
The function CallReceiveEvents(object state) may raise the event DataReceived twice, but it checks for the presence of the handler only once.
When the first event-raise happens, the application may decide to unsubscribe from this event, or even to dispose the SerialPort instance, then, when the control returns to CallReceiveEvents, it attempts to raise the same event again (without checking again against null), but, at this time, the event may be null if the application unsubscribed from it during the first event-raise, and ==> NullReferenceException; the application crushes. See the screenshot:
Reproduction Steps
- subscribe to the event SerialPort.DataReceived
 - in the event handler, unsubscribe from SerialPort.DataReceived
 - the issue happens only if the serial port has the Eof in its internal buffer.
 
The problem should be clear enough from the Description.
Expected behavior
SerialPort should check for the event against null before attempting to raise it.
Actual behavior
.NET raises NullReferenceException and the application crushes.
Looking at the source code, I noticed that all Call*Events functions have the same problem: CallErrorEvents, CallPinEvents, and CallReceiveEvents.
Regression?
No response
Known Workarounds
No response
Configuration
No response
Other information
No response
