开发者

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

开发者 https://www.devze.com 2023-02-24 05:38 出处:网络
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 i

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消