Please, help to organyze time out. I have a program which connects to another device by COM port. If device is disconnected and I try to connect this device, the time out exeption must be. Can anyone give me example of making time out here?

private void OnButton_Reading_Click(object sender, EventArgs e)
        {
            try
            {
                using (SerialPort port = new SerialPort(textBox_port.Text))
                {
                    // configure serial port
                    port.BaudRate = Convert.ToInt32(this.textBox_speed.Text);
                    port.DataBits = 8;
                    port.Parity = Parity.None;
                    port.StopBits = StopBits.One;
                    port.Open();
 
                    // create modbus master
                    IModbusSerialMaster master = ModbusSerialMaster.CreateRtu(port);
 
                    byte slaveId = Convert.ToByte(textBox_adress.Text);
                    ushort startAddress = UInt16.Parse(textBox_Register.Text, NumberStyles.HexNumber);
                    ushort numregisters = 1;
 
                    // read registers
                    ushort[] registers1 = master.ReadHoldingRegisters(slaveId, startAddress, numregisters);
 
                    string Mlb1 = Convert.ToString(registers1[0]);
                    this.textBox_Reading.Text = Mlb1;
 
 
                }
            }
 
            catch (Exception g)
            {
                MessageBox.Show(g.Message);
            }
        }

Dani AI

Generated

For a COM/Modbus reader you want deterministic I/O timeouts — not Thread.Sleep. Thread.Sleep just blocks the current thread (so a WinForms UI or thread-pool thread will freeze) and is the wrong tool for waiting on serial I/O. Instead, set the SerialPort read/write timeouts and use the Modbus transport settings or the async APIs so your UI/thread stays responsive. See the SerialPort docs for ReadTimeout/WriteTimeout and the Thread.Sleep behaviour. (learn.microsoft.com)

Set the SerialPort timeouts, configure the NModbus transport and use the async read (or run the blocking work off the UI thread). Example pattern (focuses on timeouts and error handling — not your whole form code):

port.ReadTimeout = 2000;
port.WriteTimeout = 2000;

using var master = ModbusSerialMaster.CreateRtu(port);
master.Transport.ReadTimeout = 2000;
master.Transport.Retries = 3;
master.Transport.WaitToRetryMilliseconds = 100;

try {
    ushort[] regs = await master.ReadHoldingRegistersAsync(slaveId, startAddress, count);
    // use regs[0]...
}
catch (TimeoutException) {
    // no device response — treat as "disconnected"
}
catch (IOException) {
    // serial I/O error
}

NModbus exposes transport-level timeouts/retry settings you can tune instead of catching every generic exception; it also provides async methods so you can await reads rather than blocking. Configure those transport properties to control retries, retry delay and read timeout. (nmodbus.github.io)

Practical tips: avoid catch (Exception) — catch TimeoutException and IOException so you can distinguish "no answer" vs lower-level port errors. Check SerialPort.IsOpen before calls and cleanly Dispose/Close and recreate the port on error. Use the SerialDataReceived event or the async master methods to avoid blocking reads on the UI thread. This builds on ’s point (don’t Sleep) and ’s suggestion (use timeouts) while giving the concrete NModbus/SerialPort settings to use. (learn.microsoft.com)

Recommended Answers

All 2 Replies

I don't quite understand what you're saying, but if you want to make the program wait a few seconds, use the Thread.Sleep method:

System.Threading.Thread.Sleep(5000); // waits 5 seconds

You are using the NModbus ModbusSerialMaster.
If I remember correctly this uses the serial port's timeout settings.
Set port.ReadTimeout to a suitable value (in milliseconds).
The ModbusSerialMaster will retry 3 times before failing with an exception.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.