0

So, the documentation that I've found online so far regarding the Invoke property doesn't seem to be particularly good, which is actually kind of annoying, believe it or not. I understand what Invoke does - you can't safely access the GUI directly, so an invoke does it in a safe way. That's fine, but I don't understand the variables that go into the method. If I wanted to, for instance, remove text from a listbox, how would I do that? I get about this far before I get a bit lost.

private void DoStuff(string TextIWouldBeRemoving)
{        

if (listboxname.InvokeRequired)
    {
        listboxname.Invoke(SomeMysteriousParamaters, new object[] { TextIWouldBeRemoving )};   
    }
}
Kulahan
  • 512
  • 1
  • 9
  • 23

3 Answers3

0

The first parameter is the method you want to safely invoke, the second parameter is an object array of the arguments to that method

So you would write:

private void DoStuff(string TextIWouldBeRemoving)
{        
    if (listboxname.InvokeRequired)
    {
        listboxname.Invoke(DoStuff, new object[] { TextIWouldBeRemoving )};   
    }
    else
    {
        // Actually remove the text here!
    }
}
Kevek
  • 2,534
  • 5
  • 18
  • 29
  • I would like to add: While I hope what I wrote helps you understand what you were asking and what you had written, I agree with others that there are better methods of thread management, and you should look into BeginInvoke or lambda delegates. You should likely also look into the Dispatcher, ThreadPool, and (if you need parallel execution) Parallel.Invoke. You can see some answers to this case [here](http://stackoverflow.com/questions/7320491/simplest-way-to-run-three-methods-in-parallel-in-c) – Kevek Sep 07 '11 at 14:10
  • Ohhhhh, I understand now. I didn't realize that it would actually hit the "else" statement. And yeah, I'll probably be looking into those other things, this is just a quick program I had to throw together for someone real quick. Thanks for the suggestions! – Kulahan Sep 07 '11 at 14:49
0

Invoke is all about threading.

You need to do an invoke whenever you have created a separate thread in your code, and you need to update the User Interface elements from withing the code, that is executing in that newly create thread.

You can use a BeginInvoke, instead of a synchronous Invoke method. This article has a good example:

http://msdn.microsoft.com/en-us/library/0b1bf3y3.aspx

Maxim V. Pavlov
  • 10,303
  • 17
  • 74
  • 174
0
  private void button1_Click(object sender, EventArgs e)
  {
     if (listBox1.InvokeRequired)
     {
        Action<string> d = DoAnything;
        listBox1.Invoke(d, new object[] { "Item 1" });
     }
     else
        DoAnything("Item 1");
  }

  void DoAnything(string itemText)
  {
     listBox1.Items.Remove(itemText);
  }
BlueMonkMN
  • 25,079
  • 9
  • 80
  • 146