Sign in to follow this  
UnshavenBastard

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

Recommended Posts

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]

Share this post


Link to post
Share on other sites
[quote name='arithma' timestamp='1343732160' post='4964802']
The child stream probably has a reference to the port.
[/quote]

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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this