SerialPort.Write method hanging, timeout not fired in C#

.net, c#, serial-port

Solution

I know it's an old question, which you've probably solved by now, but there's no accepted answer yet. I was having the same issue yesterday and seem to have fixed it -- were you setting the Write Timeout?

_serialPort.WriteTimeout = 500;

http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.writetimeout.aspx

Problem

I have to write a program that writes on a serial port but sometimes the call to the Write method hangs and the WriteTimeout is never fired so my program hangs indefinitely. Here is the port creation code: ``` void DetectX1BackgroundWorker_DoWork(object sender, DoWorkEventArgs e) { String[] ports = SerialPort.GetPortNames(); int i = 0; foreach (string PortName in ports) { try { Console.WriteLine("Trying to open:" + PortName); SerialPort port = openSerial(PortName); Console.WriteLine("Port is open:" + PortName); port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived); port.Write("$ST+IMEI=0000\r\n"); if (IMEIFoundEvent.WaitOne(250)) { Console.WriteLine("IMEI Found:[" + imei + "]"); if (addresses.ContainsKey(imei)) { ((BackgroundWorker)sender).ReportProgress(0, new X1Model(imei, PortName, addresses[imei])); } else Console.WriteLine("imei not in file: " + imei); } port.Close(); } catch (Exception ex) { Console.WriteLine("Erreur port " + PortName + ex.Message); } finally { i++; ((BackgroundWorker)sender).ReportProgress(i * 100 / ports.Length); } } } private SerialPort openSerial(string PortName) { SerialPort port = new SerialPort(PortName); port.BaudRate = 57600; port.DataBits = 8; port.StopBits = StopBits.One; port.Parity = Parity.None; port.ReceivedBytesThreshold = 1; port.Handshake = Handshake.None; port.DtrEnable = true; port.RtsEnable = true; port.WriteTimeout = 5000; port.ReadTimeout = 5000; if (!port.IsOpen) port.Open(); return port; } ``` Is there anything I'm missing ? I don't know if it's relevant but I'm using Serial To USB Adapters. Edit: I'm using Windows XP with .Net 4.0. The line doesnt't exceed 50 characters and ends by a EOL character.

Original source

Related problems