.NET Serial Port Woes. Converting C# Code to VB

2019-08-04 17:38发布

问题:

I'm having trouble with the SerialPort function intermittently crashing while data logging for several days. It's been a hard problem to debug and I would like to try Zach Saw's fix which he talks about here and provides code for in C#

My question is, to do this, do I need to rewrite the entire use of the Serial Port in my code?

If I use the System.IO.Ports.SerialPort module, is there a way to just do a DLLImport of SetCommState to set fAbortOnError to false, or do I need to abandon the SerialPort module entirely and write everything using the kernel32.dll?

回答1:

I'm pretty sure in this case you could import his project into your solution, and it should run just fine. Since VB and C# are both CLR languages, they both compile down to the same intermediate language.



回答2:

Check out this page

http://support.microsoft.com/kb/823179

It's got the proper declarations for SetCommState, with some example code. Zach's fix is to basically open the com port as a file first, call setcommstate, then use the serial io functions in .net. I haven't tried it but his post sounds like you shouldn't have to do much at all to your code.



回答3:

Having tested about 15 different solutions to the various problems with serial ports in .NET, I settled on using CommStudio. It's been rock solid ever since.

You can get CommStudio Express (their free version) here: http://www.componentsource.com/products/commstudio/downloads.html?rv=42917