Reputation: 522
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?
Upvotes: 0
Views: 5371
Reputation: 15242
private void AddTextToUpListBox(string text)
{
if (lbxServersThatAreUp.InvokeRequired)
{
lbxServersThatAreUp.Invoke((Action<String>)AddTextToUpListBox, new object[] { text});
return;
}
lbxServersThatAreUp.Items.Add(text);
}
You need to pass in the parameters for the method, you should also be able to pass the method directly as the delegate.
Upvotes: 0
Reputation: 1502036
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);
Upvotes: 2