2

Every time I update the view of my program from a thread other than the element was created from, I use:

if (this.table.InvokeRequired)
{
    this.table.Invoke(new MethodInvoker(delegate
    {
        this.table.Controls.Add(newRow);
        this.table.Controls.SetChildIndex(newRow, this.table.Controls.Count);
    }));
}
else
{
    this.table.Controls.Add(newRow);
    this.table.Controls.SetChildIndex(newRow, this.table.Controls.Count);
}

Even though this approach works fine, I doubt that it's the best-practice to do it that way since

this.table.Controls.Add(newRow);
this.table.Controls.SetChildIndex(newRow, this.table.Controls.Count); 

is basically the same for invoking and not invoking.

Any ideas how I could improve that?

Kara
  • 6,115
  • 16
  • 50
  • 57
libjup
  • 4,019
  • 2
  • 18
  • 23
  • If you're okay with using PostSharp, I'd recommend this [post](http://stackoverflow.com/questions/11183026/how-to-write-a-postsharp-invoke-aspect-to-simplify-cross-thread-control-updates). – Matthias Feb 10 '13 at 12:10
  • I would put the common code in Action/delegate and pass that to Invoke or just call it in the else. – kenny Feb 10 '13 at 12:14
  • I have edited your title. Please see, "[Should questions include “tags” in their titles?](http://meta.stackexchange.com/questions/19190/)", where the consensus is "no, they should not". – John Saunders Feb 10 '13 at 12:17

2 Answers2

3

You can put it in a method, then the method can invoke itself:

public void addRow(Control newRow) {
  if (this.table.InvokeRequired) {
    this.table.Invoke(new MethodInvoker(addRow), new object[]{ newRow });
  } else {
    this.table.Controls.Add(newRow);
    this.table.Controls.SetChildIndex(newRow, this.table.Controls.Count);
  }
}
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
0

The syntax might not be exactly right, but roughly:

delegate void myedelegate(<mystuff>)
void UpdateSomething(<mystuff>)
if(this.invokerequired)
{
    mydelegate updater = new mydeleate(UpdateSomething);
    updater.invoke(new object[]{<mystuff>})
}
else
{
    //doupdate
}

Also, see http://www.codeproject.com/Articles/37642/Avoiding-InvokeRequired for a good guide on invoke required practices

Immortal Blue
  • 1,691
  • 13
  • 27