Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parameter Count Mismatch

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];
            }
        }
    }
like image 323
BSchlinker Avatar asked Oct 28 '09 11:10

BSchlinker


2 Answers

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;
    }
}
like image 171
ybo Avatar answered Sep 30 '22 03:09

ybo


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]));
like image 42
SLaks Avatar answered Sep 30 '22 03:09

SLaks