2

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.

4

2 回答 2

3

我知道这是一个老问题,您现在可能已经解决了,但还没有公认的答案。我昨天遇到了同样的问题,似乎已经解决了——你是在设置写入超时吗?

_serialPort.WriteTimeout = 500;

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

于 2013-11-14T11:05:31.360 回答
0

您还需要设置PortName. 您可以从中获取端口列表GetPortNames。这通常会像COM1COM2

于 2012-04-05T13:44:01.900 回答