views:

609

answers:

2

Having trouble with the following segment of code. I'm getting a parameter count mismatch.

I've had to write this because of problems with multiple threads and unsafe updates.


       delegate void data_INPUTDelegate(object sender, System.IO.Ports.SerialDataReceivedEventArgs e);
    private void data_INPUT(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
    {
        string data = serialPort.ReadLine();

        string[] tokens = data.Split(':');
        if (tokens[0] == "$SENSOR")
        {
            if (label_sensorValue.InvokeRequired)
            {
                data_INPUTDelegate del = new data_INPUTDelegate(data_INPUT);
                label_sensorValue.Invoke(del,new object[] {tokens[1]});
            }
            else
            {
                label_sensorValue.Text = tokens[1];
            }
        }
    }
+5  A: 

I guess the error comes from this line:

label_sensorValue.Invoke(del,new object[] {tokens[1]});

You pass only one parameter to del (tokens[1]) but it has two parameters (sender and e)

EDIT: after carefully reading your code, I suggest that you create a SetSensorValue method to set the value of label_sensorValue. Right now you're trying to invoke the event handler with wrong parameters.

private void data_INPUT(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
    string data = serialPort.ReadLine();

    string[] tokens = data.Split(':');
    if (tokens[0] == "$SENSOR")
    {
        SetSensorValue(tokens[1]);
    }
}

delegate void SetSensorValueDelegate(string value);

private void SetSensorValue(string value)
{
    if (label_sensorValue.InvokeRequired)
    {
        SetSensorValueDelegate del = new SetSensorValueDelegate(SetSensorValue);
        label_sensorValue.Invoke(del, new object[] {value});
    }
    else
    {
        label_sensorValue.Text = value;
    }
}
ybo
This is actually how I rewrote the code about 10 minutes ago. Thanks though.
BSchlinker
+1  A: 

Your problem is that you're calling a two-parameter delegate with only one parameter.

The following line

label_sensorValue.Invoke(del,new object[] {tokens[1]});

invokes the delegate on the UI thread with the parameter tokens[1].

Since the delegate requires two parameters, it's failing. In addition, the delegate expects an object and a SerialDataReceivedEventArgs, not a string.

To fix this, you should invoke an anonymous method instead of the delegate.

For example (in C# 3):

label_sensorValue.Invoke(new Action(() => label_sensorValue.Text = tokens[1]));
SLaks