Let me share you with one of the weirdest errors I ever encountered. Recently, I have been working on a distributed application which is built from a server and some clients. The clients are Windows Forms applications. Yesterday, I spent a whole day chasing a very weird and strange error – I was getting an exception at the main method (unhandled exception) of the client application. Here is what I got:

image

The error description was: “Parameters count mismatch“. Well, it didn’t help me a lot, but I thought that looking at the stack trace might be a good idea. So, here it is:

image

As you can see, there is nothing helpful here because the stack trace is full of .Net Framework methods, none of those methods are mine. Well after a whole day, trying to understand what happened, I figured out what was wrong. Take a look at the very simplified version of my code:

delegate void ChangeColorEventHandler(object sender, Color color);

private void ChangeColor(object sender, Color newColor)
{
    if(InvokeRequired)
    {
        BeginInvoke(new ChangeColorEventHandler(ChangeColor), newColor);
        return;
    }
    BackColor = newColor;
}

The ChangeColor method is changing the form back color on the UI thread. This method was called due to a server request, not because of a user action. Do you see what is wrong here? I didn’t set the sender as a parameter to the BeginInvoke method. That is it! It turns out that if you get this strange error, you probably called a BeginInvoke or Invoke methods with a wrong set of parameters. After changing my code to:

private void ChangeColor(object sender, Color newColor)
{
    if(InvokeRequired)
    {
        BeginInvoke(new ChangeColorEventHandler(ChangeColor), sender, newColor);
        return;
    }
    BackColor = newColor;
}

Everything was fine. Hope it would be helpful for some of you one day…

Tags :

2 Responses to “Parameter count mismatch Error”


  1. Ali Sali

    Said on May 26, 2009 :

    Hi! :} I just want to say that i had that error too in a WPF application, take a look to that:

    Dispatcher.BeginInvoke(DispatcherPriority.Send, (SendOrPostCallback)delegate
    {
    _isErrorBorderVisible = true; this.OnPropertyChanged(“IsErrorBorderVisible”);
    }, null);

    But if i change the parameter from “null” to “this”, everything goes smooth. :}

  2. bvrwoo_3376

    Said on January 1, 2011 :

    This is a late response but when you have a delegate invocation which using object sender (which is the owning object of the handler event), you need to pass it back and not use the ‘null’. Why I don’t know but perhaps because the class using the event trigger is looking for the source object.

Post a Comment