Search code examples
c#eventsserial-portvisual-studio-debugging

why SerialDataReceivedEventHandler work only when i put break point C#?


i made an event handler for receive data from Serial Port and it's work perfectly only when i put break point and when i remove it the function doesn't invoke this is my code am already declare the port as object of SerialPort

private static void DataReceivedHandler( object sender,SerialDataReceivedEventArgs e)
{
    SerialPort sp = (SerialPort)sender;
    // sp.Open();
    string indata = sp.ReadExisting();
    Console.WriteLine("Data Received:");
    if (indata == "kitchen_light_on\r\n")
        f1.update_flag("living_light", 1);
    else if(indata == "kitchen_light_off\r\n")
        f1.update_flag("living_light", 0);
} 

port.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler); 

Solution

  • You might be running into a race condition: if you put a breakpoint before sp.ReadExisting() then the port might have enough time to receive the whole line you pretend to receive. Without the breakpoint, the call to ReadExisting() might be too early or too fast, so the port did only receive a part of the line (for instance only "kitchen_li"). If that happens, then both of your if/elseif conditions will be false and you won't see any flags updated - the event handler got called but did nothing.

    You can check for this adding two lines of code to your if/elseif statement:

    else
        Console.WriteLine("Both conditions failed, indata contains " + indata);