Search code examples
c#delegatesmethod-invocation

No overload matches delegate


Thanks to a question previously answered on this website, I've built a little block of code. Unfortunately, I've been getting an error that I don't quite understand. Here's the block of code:

        private void AddTextToUpListBox(string text)
    {
        if (lbxServersThatAreUp.InvokeRequired)
        {
            lbxServersThatAreUp.Invoke(new MethodInvoker(AddTextToUpListBox), new object[] { });
            return;
        }

        lbxServersThatAreUp.Items.Add(text);
    }

The error I'm getting is "No Overload for 'AddTextToUpListBox' matches delegate 'System.Windows.Forms.MethodInvoker'"

So I tried changing the following line like so:

lbxServersThatAreUp.Invoke(new MethodInvoker(AddTextToUpListBox(text)), new object[] { });

but if I do that, it just says "Method name expected". What am I doing wrong here?


Solution

  • MethodInvoker is a delegate with no parameters - you've got a parameter. Two options:

    • Use an Action<string>:

      lbxServersThatAreUp.Invoke((Action<string>)AddTextToUpListBox,
                                 new object[] { text });
      
    • Use a lambda expression to create a MethodInvoker:

      MethodInvoker invoker = () => AddTextToUpListBox(text);
      lbxServersThatAreUp.Invoke(invoker);