Hello @Markus Freitag
In your current code, the TimeoutException
is not being triggered because you’re using an AutoResetEvent
to wait for a response from the serial port. The AutoResetEvent
’s WaitOne
method will return false
if no signal is received within the specified timeout, but it will not throw a TimeoutException
.
If you want to trigger a TimeoutException
, you could use the ReadLine
method of the SerialPort
class with a ReadTimeout
set. Here’s an example:
public void Test_Timeout()
{
var port = new SerialPort("COM4");
port.Open();
port.ReadTimeout = 10000; // Set the timeout to 10 seconds
var commandsToSend = new string[] { "AT1", "AT2", "AT3" };
foreach (var command in commandsToSend)
{
try
{
Trace.WriteLine($"Write '{command}' to {port.PortName}");
port.WriteLine(command);
Trace.WriteLine("Waiting for response...");
// This will throw a TimeoutException if no data is received within the timeout
string response = port.ReadLine();
Trace.WriteLine($"Got response: {response}");
}
catch (TimeoutException)
{
Console.WriteLine("Read took longer than expected");
}
catch
{
Trace.WriteLine("Failed to write to port");
}
}
}
In this modified code, the ReadLine
method will block until a line is received or the timeout expires. If the timeout expires, a TimeoutException
will be thrown.
Please note that this will only work if the data you’re expecting ends with a newline character, as ReadLine
reads up to the next newline.
If your data doesn’t end with a newline, you might need to use the Read
or ReadExisting
methods and implement your own timeout logic.
Also, remember to close the port when you’re done with it to free up the resource.
If this information provided here helps solve your issue, please tag this as answered, so it helps further community readers, who may have similar questions.