Mon, September 6, 2004, 12:16 PM under
dotNET
The .NET Framework has survived until now without offering a class for serial comms in its otherwise rich class library. I guess MS thought that rs232 was becoming obsolete - or I don't know what. The fact is that, especially on CE devices, rs232 is part of everyday life. The upshot is that .NET 2.0 comes with a SerialPort class.
So can you use your COMM ports today?
In VB6 one would use the
MSComm control, which did a great job. You could still use that in your .NET apps (by hosting the ActiveX control on a Form - assuming the
license for the control exists) just be aware of various threading scenarios. In particular, things become tricky if you are using the control in a remoted server (all threads are MTA and not STA as required, so it's pretty much a dead end situation -
I ran into this a while back).
Another answer is
PInvoke. In other words, use the traditional
Win32 APIs in the .NET app. There are a number of good MSDN pages on the subject including:
1.
Serial Communications in Win32
2.
Programming Serial Connection on WinCE
The first rs232 code to appear for .net is
here. This leads us to a 3rd solution, which is to use an existing library. Apart from commercial packages and a number of
user samples, there is a very good
article with code on the MSDN mag; so you could use that!
Now, if you are working with the Compact Framework, you have to be mindful of a few facts. WinCE does not support overlapped io. Even the non-overlapped io is implemented differently on the PC than on CE (e.g. Read/WriteFile do not block on CE). Finally, the threading support of the CF is not as rich as that of the full framework. What does all this mean? Well, basically rs232 libraries designed for the desktop/full framework will not just work on CE devices with the CF.
So what is the solution?
You can use a different library depending on which platform you are targeting, e.g. download a free assembly for the CF
here. Alternatively, the shared source repository for CF has
C# code that works on both platforms!
Finally, I recommend looking at the interfaces of the
System.IO.Ports.
SerialPort in Whidbey, so that when you upgrade your code it is easy to switch one implementation out for the other. I have put an example
here.