.NET: Using a SerialPort's BaseStream after port was GC'ed

Started by
1 comment, last by UnshavenBastard 11 years, 8 months ago
Is the following behavior documented somewhere and intended & likely to remain so, for some good reason?
I saw some code that essentially did what the code below does: Create a SerialPort object in a local scope, opening it, grabbing a reference to the SerialPort's BaseStream, then losing the sole reference to the SerialPort object by leaving scope.
Then, the reference to the BaseStream is happily used. I simulate this by enforcing Garbage Collection & waiting for finalizers' completion.
When I initially saw this, I assumed that when the SerialPort gets GC'ed, it would, in the finalizer, also call dispose and in turn call Close() on its stream if it has not yet been disposed, at least, to me, it sounds like something that should be done.
Apparently, this is not the case, and I'm note sure why.

Well, why?

Besides from the fact that thus, the code seems to work - is this acceptable code "cuz you know" ? It looks to me like relying on a quirk, which seems "unclean", but then again, I might be missing something.

- unshaven

[source lang="csharp"]private void test_stuff()
{
System.IO.Ports.SerialPort com1 = new System.IO.Ports.SerialPort("COM1");
com1.BaudRate = 9600;
com1.Parity = System.IO.Ports.Parity.None;
com1.DataBits = 8;
com1.StopBits = System.IO.Ports.StopBits.One;
com1.Handshake = System.IO.Ports.Handshake.None;
com1.ReadBufferSize = 4096;
com1.WriteBufferSize = 2048;
com1.ReadTimeout = 5000;
com1.Open();

Stream stream = com1.BaseStream;

com1 = null;

GC.Collect();
GC.WaitForPendingFinalizers();

var buf = new byte[1024];
stream.Read( buf, 0, buf.Length );
}
[/source]
Advertisement
The child stream probably has a reference to the port.
[ my blog ]

The child stream probably has a reference to the port.


Duh, heh, yeah it probably has. So the whole thing is held by its feet instead of the hands.
I was so focused on "the stream should be closed" that I didn't look that way around.

I still find it a bit weird to do it that way.

This topic is closed to new replies.

Advertisement