1

So I have been working on my C# project which required to do some serial communication. Everything was working fine until I have one really... weird issue.

So right now I am recieving a code in serial which is stored in myString. Then below where I get the issue which is that if I am not debugging the code then a whole if statement just... get ignored. However when I use a breakpoint it does everything right. For referance everything here works except the part of (*l) (the rest of the code was removed for needless parts. I can attach more if you guys think it can help.)

public delegate void AddDataDelegate(String myString);
public AddDataDelegate myDelegate;
//
//
this.myDelegate = new AddDataDelegate(AddDataMethod);

//
//
private void Receiver(object sender, SerialDataReceivedEventArgs e) 
{
    Byte[] str = System.Text.Encoding.ASCII.GetBytes(comPort.ReadExisting());

    this.Invoke(this.myDelegate, new Object[] 
    { 
         System.Text.Encoding.Default.GetString(str)
    });

}
//  

private void button2_Click(object sender, EventArgs e)
{
    if (connectionStatus.Text == "Connected")
    {
        comPort.Close();
    }
    else
    {
        try
        {
            comPort.PortName = port;
            comPort.BaudRate = baudRate;
            comPort.DataBits = dataBits;
            comPort.StopBits = (StopBits)stopBits;
            comPort.Parity = parity;
            comPort.DataReceived += new SerialDataReceivedEventHandler(Receiver);

            comPort.Open();
            connectionButton.Text = "Disconnect";
            connectionStatus.Text = "Connected";

        }
        catch
        {
            comPort.Close();
        }
    }
}


public void AddDataMethod(String myString)
{
    try
    {
        string colorSensorValue;
        string distanceSensorValue;
        string proximitySwitch;
        string limitSwitch;
        if (myString.Contains("*c*"))
        {
            string[] colors;
            int red;
            int blue;
            int green;
            int max;
            colorSensorValue = myString.Substring(myString.IndexOf("*c*") + 3);
            if (colorSensorValue.Contains("*e")) colorSensorValue = colorSensorValue.Substring(0, colorSensorValue.IndexOf("*e*"));
            colors = colorSensorValue.Split(',');
            red = Convert.ToInt16(colors[0]);
            green = Convert.ToInt16(colors[1]);
            blue = Convert.ToInt16(colors[2]);

            max = Math.Max(red, Math.Max(green, blue));
            red = red * 255 / max;
            blue = blue * 255 / max;
            green = green * 255 / max;
            color.BackColor = Color.FromArgb(red,blue,green);
            colorSensorTextBox.Text = (colorSensorValue);
        }
        if (myString.Contains("*d"))
        {
            distanceSensorValue = myString.Substring(myString.IndexOf("*d*") + 3);
            if (distanceSensorValue.Contains("*e")) distanceSensorValue = distanceSensorValue.Substring(0, distanceSensorValue.IndexOf("*e*"));
            distanceSensorTextBox.Text = (distanceSensorValue);
        }
        if (myString.Contains("*l"))
        {
            limitSwitch = myString.Substring(myString.IndexOf("*l*") + 3);
            if (limitSwitch.Contains("*e")) limitSwitch = limitSwitch.Substring(0, limitSwitch.IndexOf("*e*"));
            limitRead.Text = limitSwitch;
        }
        if (myString.Contains("*p"))
        {
            proximitySwitch = myString.Substring(myString.IndexOf("*p*") + 3);
            if (proximitySwitch.Contains("*e")) proximitySwitch = proximitySwitch.Substring(0, proximitySwitch.IndexOf("*e*"));
            proximityRead.Text = proximitySwitch;
        }

        comPort.BaseStream.Flush();

    }
    catch
    {

    }

}

Example of myString:

*c*96,84,75*e**d*25.5*e**p*0*e**l*0*e*

so it will be read as: colors: 96 , 84 , 75 (happens right!) distance: 25.5 (happens right!) prox : 0 (happens right!) limit : 0 (doesnt happen..)

note that order of both sent and received data doesn't change which one (limit) that doesn't work unless I breakpoint

9
  • it's some kind of multi-threading issue Commented Nov 19, 2016 at 18:49
  • Any clue of how I can solve it Commented Nov 19, 2016 at 18:50
  • add the code you use to receive the string. are you using ReceiveData event? Commented Nov 19, 2016 at 18:51
  • Put System.Diagnostics.Trace.TraceInformation or log in each of the ifs, run the code in Release (i.e. not from VS). See if it behaves correctly. Commented Nov 19, 2016 at 18:51
  • it will not be convenient at all to run it on release since I will need to debug a lot. How exactly do I do the other two? Details would be appreciated. Commented Nov 19, 2016 at 18:53

1 Answer 1

1

According the SerialPort: class information in MSDN:

The DataReceived event is raised on a secondary thread when data is received from the SerialPort object. Because this event is raised on a secondary thread, and not the main thread, attempting to modify some elements in the main thread, such as UI elements, could raise a threading exception. If it is necessary to modify elements in the main Form or Control, post change requests back using Invoke, which will do the work on the proper thread.

You should use use this form:

this.Invoke(this.AddDataMethod, new Object[] { The_Received_String });
                    }
Sign up to request clarification or add additional context in comments.

3 Comments

so I just add ".Parent" to that part?
I'm sorry, I copied and paste from my code. I have a general purpose serial class.
The weird part is that it only skips that specific IF even when I changed the order of the IF statements. Thanks for trying anyway!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.