简体   繁体   中英

VB.NET 2005, Serial port, dispose problem, Windows CE

I write program for Windows CE that should work with Serial ports. I use object System.IO.Ports.SerialPort . Everything works well but when I close program and open it again, I receive error: Port is in use! At the end I write:

port.close()
port.dispose()

And If I add this:

System.GC.collect() 

.. than everything begins to work

But problem is that computer gets stuck when garbage collector is called for each port. If I tried to use collector somewhere else, it doesnt "collect" ports and they look like used if program starts again.

Can someone help please?

There are a few potential possibilities here. First, just because you call Close, it doesn't mean the port is physically released - this is true even in C. It depends on the state of the UART and a whole lot on how the actual driver was written. It may take time from the call to Close to the actual driver releasing the port. This, I believe, is what you're actually seeing becasue you're actually manually calling close rather than waiting for the Finalizer to destroy your Port instance and implicitly close it - this would take even longer.

Of course this assumes that your Close call is actually being run. If it's not, then you need to understand how object Finalization works in managed code. This has nothing to do with OOP, it has to do with how memory is managed. When an object does out of scope and has no more roots (references) it's available for collection, but that doesn't mean that it's immediately released. In fact it can be quite some time before the finalizer runs, especially if the app continues to run.

It could be that an object that owns the port object is not disposed or still maintains a reference. That would explain why after system.gc.collect() it works.

How long are you waiting between closing it and opening it? According to MSDN :

The best practice for any application is to wait for some amount of time after calling the Close method before attempting to call the Open method, as the port may not be closed instantly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM