WARNING! SerialPort in .NET 3.5. RRS feed

  • General discussion

  • WARNING! There are indications that SerialPort has been changed in VS 2008 and .NET 3.5 in such a way that most code written for .NET 2.0 may not work or even worse - it may lock the COM ports FOREVER! In fact, there seems to be so many errors in SerialPort 3.5 that it may be regarded as useless! For the moment the following problems have been reported, but it is too early to tell what courses these problems and how to fix them:

    • It may crash if you access the modem control signals while the port is receiving.
    • It may crash if you try to close a port set to a wrong speed - even if you have an error handler for the ErrorReceived event.
    • You cannot use multiple ports.
    • If you try to run a 3.5 application generated under Vista on a XP PC, it may look up the COM ports FOREVER making them useless for all programs including Hyperterminal - even if you delete the program again.

    VS 2008 allow you to select the wanted .NET version when you build your application. Be sure to select 2.0 to avoid all these problems.

    Saturday, January 5, 2008 10:19 AM

All replies

  • Cartsen,


    Thanks for the alert, just to clarify the issue I had w/SerialPort under 3.5


    -erratic behavior (difficulty getting it to dispose, large cpu usage, properties work intermitantly) on the computer it was created

    -has apperantly locked up the comports on a different computer, this is the determination of the lead engineer of my work. As to the how, why and extent of what the app did hasnt yet been determined or if its reversible.


    Recompiling the same app under 2.0 and all the issues of encountered on the source computer have resolved, no Idea if it itll work on another or not.



    Saturday, January 5, 2008 8:13 PM
  •  Carsten Kanstrup wrote:
    VS 2008 allow you to select the wanted .NET version when you build your application. Be sure to select 2.0 to avoid all these problems.

    For reference, I changed this setting under My Project, Compile, Advanced Compile Options, Target Framework. The change required a close/open of VS, then I noticed it didn't like some of the references that are new in the 3.5 framework such as XML. I removed the ones it didn't like from the References tab under My Project.

    I was then left with one last error message: "Namespace or type specified in the project-level Imports 'System.Xml.Linq' doesn't contain any public member or cannot be found." In the References tab, under Imported namespaces, I had to uncheck System.Xml.Linq. The error was gone, the project compiled, and the serial connection acted normal based on what little testing I did.

    Carsten, great work on finding the serial bugs in 3.5.

    Sunday, January 6, 2008 1:24 AM
  • I hope you have submitted these as bug reports and if so, maybe you should post the link so people can vote on the bugs so that they get more attention.




    Monday, January 7, 2008 3:16 PM
  • Hi Chris


    Geat suggestion, problem is Im fairly new to .NET and very new to this forum, can you point me in the right direction or faq on how to report bugs?


    Just to update my situation;


    Recompiling the app w/2.0 cured the odd nuances I was expereincing on the source computer.


    The client computer comports were not fixed by add/remove of the 3.5/2.0 framework alone. I also had to repair/install windows to return the comports to their funtionalility prior to the loading of the app. Since then I have reloaded 2.0 framework and the app with no issues other than some conflict issues I have (which I expected)  running my app while running an old VB6 app simultaneously.




    Tuesday, January 8, 2008 3:48 AM
  • Chris


    I have not reported the bugs yet, but of course I will as soon as I get a better overview of what is going on. All the reported bugs are based on reports from others. I have not tested .Net 3.5 myself (I usually wait for the first SP :-) ) and of course the bug with the port lock-up cools down my interest of trying it! I just wanted to bring the warning out as soon as possible and I have also posted it in the base class forum and in my SerialPort description in our knowledgebase.


    I will try to get in contact with Kim Hamilton, who is the one, who has programmed SerialPort. There were some serious flaws in version 2.0, which made it useless for many modern communication methods like telegram separation by means of break, 9th bit communication and automatic unit addressing, and since version 3.5 is useless, maybe it is time for a collaboration about a good serial port implementation?

    Tuesday, January 8, 2008 8:55 AM

    ...maybe it is time for a collaboration about a good serial port implementation?


    Yes please

    Wednesday, January 9, 2008 4:15 AM
  • System.IO.Ports namespace (which contains all the SerialPort functionality) resides in the System.dll assembly that seems not to have changed at all with the advent of.NET 3.5

    .NET 3.5 Framework is actually a .NET version 2.0 runtime only with some new .dlls added for the new tricks, but the old things remaining to use the same .dll assemblies as in 2.0.


    I am about to port one of my applications using serial ports to .NET 3.5 (I need the new WCF stuff) so it is not quite clear to me what changes in the serialport functions whether I compile to 2.0 or to 3.5 if the Sytem.dll with the System.IO.Ports namespace is the same in both cases.


    Is there any progress location this bug ?

    Wednesday, February 6, 2008 6:16 PM
  • Unfortunately, there is no progress. I have tried to get in contact with Kim Hamilton, who is responsible for SerialPort, but so far without success.


    It is a mystery what happens, but there is no doubt that there is a difference. Many applications including my own do not work with .Net 3.5. Maybe the bugs have been introduced when Microsoft tried to fix the bug, which gave an unhandled exception if you remove a USB-Serial converter during transmission.


    Microsoft has not been very informative about the interior of .Net 3.5 and the changes made. For example, I have heard that the event handling has been changed and that Application.DoEvents no longer exist, but since I have not tried 3.5 myself, I have not been able to verify these rumours. With all the reports I have seen about the SerialPort problems in 3.5, I am not in a hurry of trying it myself! I have to finish a hardware/software project within a few month and don't need any new problems right now!

    Wednesday, February 6, 2008 7:00 PM
  • I have a similar problem with the SerialPort object.

    The Hyperterminal reads the serial port data and the SerialPort object don’t receive any data.

    The application was compiled in VS2008 but with .Net Framework 2.0 as a target.

    I try an external USB to serial converter and I have the same problem.

    Some ideas???

    Thanks, and sorry for my bad English!

    Juan Segura



    Friday, March 7, 2008 12:07 PM
  • Although there are many flaws and bugs in SerialPort, it is not completely "dead". I presume that you have made a mistake. Show us some code.

    Friday, March 7, 2008 1:01 PM
  • There is hope - at least some!


    I have just received a short note from Microsoft that the status of my error report has been changed from Active to Resolved. "Of course" they have not made any description of what they have done and when the changes will be available - even though I had given my e-mail address and asked for a dialogue. Although the present SerialPort implementation clearly shows that the ones, who is responsible for this, do not know much about serial communication and the possibilities of modern UART's, they obviously still thinks that they cannot learn anything from us ordinary mortals - sad!


    For years, Microsoft has hoped that the serial port would go away, but today there are even more serial port application than ever before due to GPS devices etc. and I have got three stars on my shoulders almost only answering serial port questions. I really hope that Microsoft finally will give the port the attention it deserves and at least try to find somebody, who knows about serial port hardware (modern UART's and USB-serial converters) if they don't want to discuss the subject with somebody outside Microsoft.


    Thursday, March 13, 2008 8:46 AM
  • OK, OK,
    I cannot understand why a new version can handle more bugs than the the older one. Did Microsoft imagine that we are professionals using tools to make our work. I spent 2 days of my work trying to make my Serialport object work. Who will pay for that, my customer ? Only because I use Microsoft's labnguage beacause they are the "leader".

    As son as I removed the app.config file from my project saying that System.dll has to be takem from .Net Framework 3.5 in place of 2.0 everything works well !

    I cannot understand why Microsoft don't SELLS working things before completely testing them. It is the reason for what I spent 2 days debugging my app before to send it to my customer, why doesn't Microsoft do the same ?

    Wednesday, August 13, 2008 1:13 PM
  • This is what I received from Microsoft July 26th 2008.


    "The following feedback item you submitted at Microsoft Connect has been updated:

    Product/Technology - Visual Studio and .NET Framework - English
    Feedback ID - 321557
    Feedback Title - SerialPort in .Net 3.5 so full of errors that it is useless!

    The following fields or values changed:

    Field Status changed from [Resolved] to [Closed]"


    Problems not solved, no solution send, .Net 3.5 probably still full of errors and nothing done, BUT CASE CLOSED !!!


    Indeed a profesional way of handling problems!

    Wednesday, August 13, 2008 2:58 PM
  • SP1 for VS2008 and .Net 3.5 were released on 8/11/2008. I'm going to speculate that the serial port fix is in one of those.

    Personally, I'm going to stick with .Net 2.0 for a while, as I have no real need to run 3.5.
    Wednesday, August 13, 2008 5:51 PM
  • Hi Carsten,


    I just wanted to let you know that I've clarified the status of the Connect Bug.  The status shows it as Closed (External) because we're tracking the overall request to improve SerialPort in a separate internal database that we use to track suggestions.  I'll look into seeing if we can get the bugs linked appropriately such that the external connect status reflects the actual status of the internal bug.


    Also, to clarify our releases:

    .NET 3.0 RTM = .NET 2.0 RTM + new .NET 3.0 RTM assemblies

    .NET 3.5 RTM = .NET 2.0 SP1 + .NET 3.0 SP1 + new .NET 3.5 RTM assemblies

    .NET 3.5 SP1 = .NET 2.0 SP2 + .NET 3.0 SP2 + .NET 3.5 SP1 + new .NET 3.5 SP1 assemblies


    We made very few changes to Serial Port in 2.0 SP1, only fixing a few bugs:

    • Race condition between SerialPort.Close and event loop runner shutting down
    • Serial IO WaitCommEvent enters high CPU and leaks memory when USB Serial Port removed
    • (Internal Regression) SerialPort.ReadExisting() returns incorrect characters

    We made only one change to Serial Port in 2.0 SP2, fixing the following bug:

    • UnauthorizedAccessException in SerialStream crashes application after disconnecting device from USB COM port

    This should fix the main issue that you reported of the unhandled exception when disconnecting a device from a USB COM port.


    It's possible that other, unrelated, bug fixes that went in to 2.0 SP1 and 2.0 SP2 caused regressions in Serial Port since 2.0 RTM, but we have a very high bar for changes that go into service packs.  If you are seeing any issues in 2.0 SP2 (i.e. 3.5 SP1), please let us know and provide steps to repro the problem.


    I'd love to have a discussion on any other blocking issues in 2.0/3.0/3.5 and the list of improvements you'd like to see in a future release.  While I can't guarantee we'll address everything, we'll certainly prioritize the most egregious issues.


    Please check the connect bug and let me know if the email address you originally provided is still the best way for me to get in touch with you to discuss offline.


    Hope this clarifies things!




    Justin Van Patten

    Program Manager

    Common Language Runtime, Base Class Libraries

    Friday, August 15, 2008 11:53 PM
  • Yes. mail @ innovatic dot dk is still the best way to contact me.


    It seems that your attempt to fix the USB disconnect bug has coursed so many problems with SerialPort in .Net 3.5 that it is useless - see the big warning on the first page of my serial port totorial: http://www.innovatic.dk/knowledg/SerialCOM/SerialCOM.htm . There are even reports that shows that your bug fix doesn't work!


    I must admit that I am not in a hurry of trying a new version, which may course a permanent disabling of my serial ports until I reinstall Windows! Let me suggest that you turn back to the version 2.0 implementation until you have a full overview of the consequences of the bug fix attempt. It is better to have a port with a small known bug that a completely useless implementation.


    Please let me know if I can contribute to a modern SerialPort implementation. If you don't want to discuss this with anybody outside Microsoft, please find somebody with at least some hardware knowledge.


    The Microsoft serialport implementation is stone age. For example, you cannot use any of the modern communication methods like 9th bit communication, automatic unit addressing and telegram separation by means of break. The reason for this is that Microsoft takes 11 bits from the receiver FIFO in the UART, throws the three vital upper bits - framing error, parity error and break - away and stores the 8-bit result in a 16-bit stream. Sorry to say it, but how stupid can you be? There is a reason why the UART manufactorers have made the receiver FIFO 11 bit wide instead of only 8! It is not enough to make an error or break event. You need to maintain full synchronization between the flags and the received bytes to point out a break byte or a byte with parity error, which is used for 9th bit communication.


    In our new fieldbus system Max-i, which will be released Q3, we use break to separate binary telegrams up to 1.843 Mbit/s. Breaks gives us the 257th state we need (all 256 binary values from 0-255 are used). We have to use a special (and expensive) kernel mode driver for this because at that speed we may have received several telegrams when the event handler for break gets up and running so it is impossible to tell which 00 bytes are actually breaks.


    In the old days with 20-mA communication, break was used to indicate a broken line, but the fools, who defined the RS-232 standard, destroyd that possibility so from RS-232, break has lost its original meaning, but is still very useful to separate binary telegrams where all 256 values are used. Unfortunately Microsoft has not left the 20-mA age although no PC has 20-mA serial ports.


    I have reported this problem long time ago to Kim Hamilton, but nothing seems to happen. For years, Microsoft has hoped that the serial port would disappear, but today there are even more serial port applications than ever before due to GPS devices etc. I have even got "three stars on my shoulders" almost only answering serial port questions, so it must be a very big problem for many.



    Saturday, August 16, 2008 1:14 PM
  • Hi,

    I'm new to forums so excuse me if this has been answered else where.

    I am writing an application in VB2008 and have fallen foul of the USB bug where one gets an 'Unhandled Exception'
    when the program ends after removing a USB device.

    I guess I have three questions:
    1a) If I roll back to an earlier version of .NET will this resolve my USB problem?
    1b) How does one go about compiling with an older version?
    2) Is there a fix to capture the error message using version 3.5 yet?

    Thanks for any assistance
    Monday, September 8, 2008 8:09 AM
  • 1a) No.


    1b) You can select the wanted .Net version in VS2008. Since I still use VS2005, I don't know exactly where to select it, but I know that the possibility exists. Be sure to select .Net 2.0 for all serial port applications.


    2) Microsoft has tried to fix the bug in .Net 2.0 SP2 and .Net 3.5. However, I have seen reports that it doesn't work, but since .Net 3.5 is useless anyway for serial port applications, you need to use .Net 2.0. As you can read in this thread, the problem ought to be fixed in SP2, but as you can also read, there is a risk that the many problems was introduced already with SP1 or SP2 for .Net 2.0!


    It is a mess and nobody seem to do anything serious about it. As you can read in this thread, Microsoft asked for my contact information, which I gave them, but so far I have not heard anything.


    You can find the following half-way bug fix on this address: http://blogs.msdn.com/bclteam/archive/2006/10/10/Top-5-SerialPort-Tips-_5B00_Kim-Hamilton_5D00_.aspx


    <?xml version ="1.0"?>
        <legacyUnhandledExceptionPolicy enabled="1"/>

    Tuesday, September 9, 2008 4:34 PM
  • 1b) Go back to page 1 of this thread, and read the 3rd post (from me). That describes how to compile with .Net 2.0 in VB2008.

    I still haven't bothered to test the serial stuff with .Net 3.5 now that SP1 has been released. I have been compiling with 2.0 and my app runs great with serial data.

    If you still have the USB disconnect issue and that is a problem for you, then you might look into some other serial connection. I used one called DesktopSerialIO for a while prior to figuring out that microsoft's serial stuff in 3.5 didn't work. I'm not sure if DesktopSerialIO can handle the USB disconnect, but it might.
    Wednesday, September 10, 2008 2:20 AM
  • So I tested serial in .Net 3.5 SP1 with VB2008 SP1, and it seems to work. The device I used is a GPS receiver, so the data stream is one way at 4800,8,N,1. I tested it with my application and with Carsten's MaxiCOM application. Both programs showed me the data stream, which is something I couldn't get to work with .Net 3.5 RTM.

    I'm using a USB-to-RS232 converter cable, so I also checked to see what would happen when unplugging the cable. Obviously the data stream stops, but the program still seems responsive for a bit. Eventually I get a debug error saying "UnauthorizedAccessException was unhandled" "Access to the port is denied'.

    Re-compiled in .Net 2.0 again, pulled the USB cable, and the data stream just stops. No error, no crash, nothing. Acts like it should. If I try to reconnect, the error is trapped and the user gets a message that the port is unavailable.
    Wednesday, September 10, 2008 3:10 AM
  • Hi,


    Thanks for the replies.


    I tried using .Net 2.0 and now have an additional error saying there is a missing .DLL - but I think this will be easy to sort out.


    I'll give the Unhandled Exception 'Half-way' fix a go and see if it captures the exception. At the moment I have shipped the code and waiting for the customer to get back to me!






    Tuesday, September 16, 2008 1:16 PM
  • Are there any further notes about this failure, and any indications of a fix date? 

    I am currently seeing a serialPort in .NET 3.5 locking up my entire desktop when received data is sent into a locked read buffer.  The rate of the failure is random.  I will be doing additional debug and troubleshooting in an attempt to locate the exact failure, but I'm quickly tiring of rebooting my entire system each time it locks up during testing.

    Added on 10/20/08:

    Issue tracked to not be due to .NET.  My apologies for my mistake.
    Thursday, October 16, 2008 10:25 PM
  • Unfortunately, there is nothing new. SerialPort in .Net 3.5 RTM is useless, but SP1 seems to work - at least in some cases.


    I hope to get in dialogue with Justin Van Patten from Microsoft about this. If you are using SP1, please give a little more detailed description of your problems.


    Saturday, October 18, 2008 6:31 AM
  • Thanks Carston, I actually did find my problem.  The Free Serial Port Monitor from here has a bug in it when running under 115200 that locks up the PC.

    I have been able to use that serial port monitor before, even with 115200, with C++ and Win32 based programs, and I've never had a crash before. 

    As well, I am currently using SP1 and running with a single serial port (for now) and I will be expanding to using multiple serial ports (each on a different thread) as well as USB->Serial converters.
    Monday, October 20, 2008 7:38 PM
  •  jkanta wrote:

    As well, I am currently using SP1 and running with a single serial port (for now) and I will be expanding to using multiple serial ports (each on a different thread) as well as USB->Serial converters.


    With a single usb to multiple rs232 converter?


    I attempted this (multiple rs232 app) using one to one usb to rs232 converters and could never get it to work. I wound up going rs485.

    Monday, October 20, 2008 8:08 PM
  • Multiple USB -> Serial port converters was my plan, but I'm a little nervous after reading the problems so many of you have had.  Can anyone spell out specifics about their failures to use multiple serial ports?  Is this limited to the USB -> Serial converters or is it something about any serial ports?
    Monday, October 20, 2008 8:46 PM
  •  jkanta wrote:
    Multiple USB -> Serial port converters was my plan, but I'm a little nervous after reading the problems so many of you have had.  Can anyone spell out specifics about their failures to use multiple serial ports?  Is this limited to the USB -> Serial converters or is it something about any serial ports?


    No, it was some time ago and it was a total pita and we never got it to work. I was the guy doing the embedded firmware side and tried to help the guy who was writing the pc software side. We then decided to use one rs232 and do signal multiplexing, which worked for short distances, but signal degradation became an issue. Ultimately we wound up using rs485, which is what we should have done in the first place. The only downside to doing this was having to change or communication protocal that we had in place.


    Not to say youll have issues, but we did. The biggest issue we ran into using multiple converters was how windows enumerated them. If your going rs232 I would definatley look into single usb to muti rs232.



    Monday, October 20, 2008 9:19 PM
  • Don't forget you probably saved much more time than 2 days because of vb and .net's many very good advantages over C++. Using new functions often doesn't require any time spent looking up manuals because the background compiler helps you as you type. A lot of basic tasks are done for you, like anchoring controls, backgroundworker, loading JPGs, autocompleting For..Next loops, autoindenting, autocomplete, etc.

    Autocomplete is in my opinion one of the most effective tools because it allows you to use long descriptive variable names without having to type them in all the time. This enhances maintainability as well as speeding up the initial coding.

    I've suffered from similar frustrating bugs, but on the whole I'm still pleased with how well designed most of it is.

    Tuesday, October 21, 2008 2:25 AM
  •  CORRECTION: The problem of not closing the port across reboots was my own. A third party application was opening COM1 through COM10 before my application had a chance to open ports.  I am still using .NET 2.0 though which seems to be much more reliable than .NET 3.5 for Serial Communication.


    I was using .NET 3.5 SP1 with a USB to Serial adapter and  getting a "Blue Screen" kernel crash on two different computers. I rolled my console application back to .NET 2.0 SP1 and the crash has gone away. I still get a problem where the port does not close, even across reboots. Disconnecting it and reconnecting works around this issue, but it is still not good.  I have another application using .NET 3.5 with a real COM1 serial port, which has worked pretty well.

    Summary: I think the USB to Serial driver is not good which is made worse by using .NET 3.5. I don't know if this implies that a new bug exists in .NET 3.5, but just that the functionality is not as stable. I don't like creating applications that are a mixure of .NET versions, but I see no other easy solution.  There may be a nasty bug lurking in my code which is just hidden by using .NET 2.0.  I hate it when there is not a clear reason why a crash occurs.

    I sure would like it if MS would test .NET 3.5 with various USB to serial adapters and make .NET more bullet proof.

    As a faily complicated example, my application opens a real COM1 serial port, a COM3 USB to serial port and a COM4 virtual serial port connection.  Incomming data on COM1 and COM3 triggers event messages which are piped through event handlers to the main thread (console application). The console application then writes commands to the COM4 virtual port. My crash was occurring while working with just the COM3 USB to Serial port. At first I thought two or more threads were writting to the same log file which was ultimately not the problem at all.

    I think I ran into every problem .NET serial ports could have. I hope these comments help someone.

    Tuesday, December 16, 2008 5:39 AM
  • I am using VB2008 and .NET3.5. Everything works fine, except this one thing: I am having a pretty major issue with the Serial Port, and can't seem to locate any information on it. If I remove a USB to serial port adapter while I have the serial port open, the serial port becomes locked in that I cannot use it again until I reboot the PC.

    I can close my software and reopen it, the port is verified to be closed before re-opening, and error handlers are used. Nothing has any effect. Even once my app is closed, another app cannot open the serial port. This occurs between multiple different types of adapters, so I know it's not my adapter or it's drivers.

    This program is to be used in a work environment where people will occasionally pull out the adapter, and so this is completely unacceptable. I need a solution, and fast. Thank you, Travis
    Monday, July 6, 2009 4:54 PM
  • I believe the product is caused by a combination of .NET3.5 and existing USB/Serial drivers. You can probably use the WDK and the command devcon to disable and then re-enable the USB port which should avoid having to reboot. But I would also suggest using .NET2.0 just for the serial port code.

    devcon status USB*
    devcon findall =ports

    devcon disable <SPECIFIC USB PORT>
    devcon enable <SPECIFIC USB PORT>

    Monday, July 6, 2009 5:23 PM
  • Carsten, with .NET 4.0 RC ready, has there been any word on the issues you raised regarding Serial Ports being addressed?

    I'm working in a GPS application and device uses COM port.

    Monday, March 22, 2010 3:08 PM
  • Justin:


    With .NET 4.0 out, has any significant work been done on resolving the Serial Port issues raised here or am I best off developing in .NET 2.0?

    I am working on a GPS application and the GPS device uses a COM port.

    A windows service similar to the Mobile GPS Intermediate Driver in .NET 4.0 would be nice. Is there one? 


    Monday, March 22, 2010 3:42 PM
  • My original com library was locked to FW 2.0 which at the time I received better results. In the last six months I rolled it forward to the latest 3.5 FW and so far all is good. I am using multiple ports, the speed is not changing though and generally the port is opened on boot to test the port then is closed and my main application then opens it for the duration. When opening it to test, I try up to five times to open the port since windows frequenly has not made the serial ports available yet. I also loop when closing to make sure the port is closed. I put all this in just to make the system more robust. Heres some code to help!

    namespace MyLib.Com
    	// Class that publishes an event
    	public abstract class MyLibSerialPort
    		public bool _continue;
    		public SerialPort _port;
    		public SerialPortParams spp;
    		public Thread readThr = null;
    		public string _DeviceName;
    		private void SetDeviceParams()
    				if (_port == null)
    					_port = new SerialPort();
    				// Common Device Port Settings
    				_port.PortName = spp.portName;
    				_port.DataBits = spp.dataBits;
    				_port.StopBits = spp.stopBits;
    				_port.Parity = spp.parity;
    				_port.Handshake = spp.handshake;
    				if (spp.readTimeout > 0) _port.ReadTimeout = spp.readTimeout;
    				if (spp.writeTimeout > 0) _port.WriteTimeout = spp.writeTimeout;
    				// Light Controller III and ISIM II Port Settings
    				_port.BaudRate = spp.baudRate;
    				_port.NewLine = spp.newLine;
    				_port.RtsEnable = spp.rtsEnable;
    				// Extended Parameters
    				_port.DtrEnable = spp.dtrEnable;
    				if (spp.receivedBytesThreshold > 0) _port.ReceivedBytesThreshold = spp.receivedBytesThreshold;
    				if (spp.readBufferSize > 0) _port.ReadBufferSize = spp.readBufferSize;
    				if (spp.writeBufferSize > 0) _port.WriteBufferSize = spp.writeBufferSize;
    				if (spp.parityReplace != (byte)'0') _port.ParityReplace = spp.parityReplace;
    			catch (Exception e)
    				Trace.WriteLine("Error(SetDeviceParams):\n" + e.Message + e.StackTrace);
    		public abstract MyLibComCmdArgs HandleMessage(string DeviceMessage);
    		public abstract void OnOpened(string message);
    		public abstract void GetVersion();
    		public abstract void Read();
    		public abstract void Write(string cmd);
    		public virtual event EventHandler<MyLibComCmdArgs> AppMessageHandler;
    		public virtual void Open()
    			int Attempts = 1;
    			_continue = false;
    			while (Attempts <= spp.OpenAttempts)
    					if (_port.IsOpen)
    						// If an exception occurs and port is already open just break
    					HandleDeviceMessage("MyLib_Info_Checking for " + _DeviceName + " on port \"" + spp.portName + "\". Attempt " + Attempts.ToString() + " of " + spp.OpenAttempts.ToString());
    					if (_port.IsOpen)
    						_continue = true; // Enable reading
    						OnOpened("MyLib_Info_" + _DeviceName + " port \"" + spp.portName + "\" opened.");
    				catch (Exception ex)
    					HandleDeviceMessage("MyLib_Err_" + ex.Message);
    			if (!_continue)
    				HandleDeviceMessage("MyLib_Err_Could not open " + _DeviceName + " on port \"" + spp.portName + "\".");
    		public virtual void Close(bool respond)
    			int Attempts = 1;
    			bool closeState = false;
    			_continue = false; // Disable reading
    			while (Attempts <= 5)
    					if (_port != null && _port.IsOpen)
    						HandleDeviceMessage("MyLib_Info_Closing port \"" + spp.portName + "\". Attempt " + Attempts.ToString() + " of 5");
    						closeState = true;
    						if (respond)
    							HandleDeviceMessage("MyLib_Info_Port \"" + spp.portName + "\" closed.");
    						closeState = true;
    				catch (Exception ex)
    					HandleDeviceMessage("MyLib_Err_" + ex.Message);
    			if (!closeState)
    				_continue = true; // Re-enable reading
    				HandleDeviceMessage("MyLib_Err_Could not close port \"" + spp.portName + "\".");
    		public virtual void HandleDeviceMessage(string message)
    				MyLibComCmdArgs result = HandleMessage(message);
    				if (AppMessageHandler != null)
    					AppMessageHandler(this, result);
    			catch (Exception e)
    				Trace.WriteLine("Error(HandleDeviceMessage):\n" + e.Message + e.StackTrace);
    		public enum CmdTypes
    		Info = 0,
    	public class MyLibComCmdArgs : EventArgs
    		private string _command;
    		public string Command
    			get { return _command; }
    			set { _command = value; }
    		private CmdTypes _type;
    		public CmdTypes Type
    			get { return _type; }
    			set { _type = value; }
    		private string _message;
    		public string Message
    			get { return _message; }
    			set { _message = value; }
    		private bool _console;
    		public bool Console
    			get { return _console; }
    			set { _console = value; }
    		private string _device;
    		public string Device
    			get { return _device; }
    			set { _device = value; }
    		public MyLibComCmdArgs()
    			_command = "";
    			_type = CmdTypes.Info;
    			_message = "";
    			_device = "";
    			_console = false;
    		public MyLibComCmdArgs(string Command, CmdTypes Type, string Message, string Device, bool Console)
    			_command = Command;
    			_type = Type;
    			_message = Message;
    			_device = Device;
    			_console = Console;
    Monday, March 22, 2010 5:01 PM
  • RickT_RSTC

    I don't know if there are any problems with SerialPort in .Net 4.0. I have not tried it yet myself, and I have not seen any bug reports. There is only one way to find out - try it.


    Everything should be made as simple as possible, but not simpler. Any fool can write code that a computer can understand. Good programmers write code that humans understand.
    Tuesday, March 23, 2010 8:54 AM
  • I am using .NET 3.5 and am having problems with hardware flow control.  Setting Handshake.RequestToSend is not properly throttling writes.  So I have set Handshake to None and I am trying to control writes using CtsHolding.  When CtsHolding becomes false, I spin on the value waiting for it to become true.  CtsHolding will then throw a System.IO.Exception.  So hardware flow control is not working.

    Wednesday, June 23, 2010 7:13 PM
  • I need to correct my previous post.  When I was spinning on CtsHolding and getting the exception, my writes were writing 1 line of data.  I changed the code to check CtsHolding, and if true, would write 1 byte.  The exception no longer appeared.  However, this was still not properly throttling writes, and I never saw CtsHolding go false. Carsten Kanstrup has pointed out in other threads that the standard PC UART does not support hardware flow control.

    Friday, June 25, 2010 5:45 PM
  • Yes, the standard UART 16C550 has no hardware flow control - except for UART's from Texas Instruments. It will empty the transmitter FIFO no matter if CTS is low. To use hardware flow control, you need a better UART - for example the 16C650-16C950 series - and you need to set the flow control from the control panel - Control Panel / System / Hardware / Device Manager / Ports (expand to see available ports) / COMx (double click on wanted port).  The software flow control in SerialPort shall then be set to "None". Note that even though you select Hardware Flow control in SerialPort, you don't get it - just a software implementation of CTS/RTS flow control, which is too slow for any practical use and will not hold back the transmitter FIFO in the UART!

    PS. Always start a new thread for a new subject. Your question has nothing to do with the subject of this thread.


    Everything should be made as simple as possible, but not simpler. Any fool can write code that a computer can understand. Good programmers write code that humans understand.
    Saturday, June 26, 2010 12:31 PM
  • hi friend,

     I read these thread very interestingly. I got the issues in .net 3.5 for serial post communication. Now i am in the development of services controlling serial port.

    My tasks are;

      1. Receive packet from serial port and send packets to serial port.

     2. Send and recieve SMS using USB GPS modem.

    Actullay my old college wrote all these services in .net 2.0 (VB) with MS communication control. But more errors are coming from that side so i am the resposible person to rewrite all these services . 

    All services are run at a time so one service will handle send and recieve via one port. Another service will handle sms using another port. I wrote this services ( not fully) in .net 3.5 using System.IO.SerialPort.

    After reading this thread i am confused. Some of my services are ready for testing. Please guid me according to my scenario which one best? Am i need to change .net version? Any issue came in these scenario?  

    Tuesday, July 6, 2010 7:36 AM
  • You can use .net 2.0 or .net 3.5 SP1. It really doesn't matter as long as you don't use .net 3.5 RTM. If you intend to use 3.5, be sure that you use SP1.
    Everything should be made as simple as possible, but not simpler. Any fool can write code that a computer can understand. Good programmers write code that humans understand.
    Tuesday, July 6, 2010 9:13 AM
  • thanks friend. i will update and use 3.5 sp1 and give the feedback..

    Please clarify this also. I have .net framework 3.5SP1 in add/remove programs.

    But in my Applicatio properties -> target framwork it is .net framework 3.5

    So it is sp1 or normal one is using

    Tuesday, July 6, 2010 9:43 AM
  • Can't say for sure, but if you have installed SP1, it is probably OK.



    Everything should be made as simple as possible, but not simpler. Any fool can write code that a computer can understand. Good programmers write code that humans understand.
    Wednesday, July 7, 2010 5:34 PM
  • k thanks..

    Actually i read your article and i got more ideas about serial port. I am in one product which communicating through serial port.. I am facing some issues there. IF you can please help to give a good solution. Issue thread is http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/90482739-08c9-400d-b3d9-d0bfe1109601

    You can find my current issue in tha last port of that thread

    Thursday, July 8, 2010 3:55 AM
  • This reply is also posted in the other forum.

    I am not a C# expert, but I can't find anywhere in your BeginInvoke statement where you specify the method on the UI thread to invoke (ReadData). I don't think that you understand how delegates are used. Read at least the chapters "Delegates", "Standard Delegates", "Invoke, BeginInvoke and EndInvoke", "Control. Invoke/BeginInvoke" and "SerialPort Receive" of my tutorial again.

    Your basic problem is that you expect a given number of bytes to be received when the DataReceived event fires. It will never work.

    Make a "Do - Loop Until" or a "While" loop, which collects one entire telegram, before you marshal it to the UI thread by means of BeginInvoke or Invoke.

    ANY good communication protocol has some method to be able to separate the various telegrams even in case of errors and missing bytes. In an ASCII protocol, you can choose a termination byte (NewLine character) and then use ReadLine to handle the protocol. In a binary protocol, it is more complicated, but as equal important. Our new fieldbus Max-i uses Break, which is very simple and very effective, but unfortunately, this is not supported by Microsoft. You can also choose a start flag and then repeat that byte every time it is data and not a flag. In this way, you know that a single occurrence of that byte is a flag, but unfortunately, it gives you the start of the telegram and not the termination.

    Since your new question has absolutely nothing to do with the subject of this thread and is a C# question, let us continue in the other forum.


    Everything should be made as simple as possible, but not simpler. Any fool can write code that a computer can understand. Good programmers write code that humans understand.
    Thursday, July 8, 2010 9:20 AM
  • thank i will look in to that thread
    Thursday, July 8, 2010 9:43 AM
  • I am working in .Net 4.0 using a custom class derived from System.IO.Ports.SerialPort, and am using multiple ports. ( USB to serial adapters to receive from more than one port: COM3, COM4...) I was receiving some data on the wrong port, and found a static string was causing the problem.

    each port is created with COMport thisPort = new ComPort();

    public class COMport : SerialPort
        public bool openPort()
             ....set Name, baud, bits... 
            DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(serialComPort_DataReceived);

        internal void serialComPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
            bool useSender = false ;
            if (useSender) // can use the 'sender', both work properly

                string indata = (sender as COMport ).ReadExisting();
                Debug.WriteLine("SerialPort Received: " + (sender as COMport).PortName + " " + indata);
                (sender as COMport ).myDriver.processReceivedMessage(indata);
            else {
                string indata = ReadExisting();
                Debug.WriteLine("SerialPort Received: " + PortName + " " + indata);

    • Edited by Kim Gregory Thursday, September 29, 2011 5:39 PM
    Thursday, September 29, 2011 3:43 PM
  • Hi Kim,

    What static string cause the problem? How can you solve it? Thx.

    Wednesday, August 22, 2012 9:17 AM