Skip to content

SerialPort: NullReferenceException #119156

@ernest-morariu

Description

@ernest-morariu

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:

Imageack to

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

Metadata

Metadata

Labels

area-System.IO.Portshelp wanted[up-for-grabs] Good issue for external contributorsneeds-further-triageIssue has been initially triaged, but needs deeper consideration or reconsideration

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions