Scott Scott - 2 months ago 5
C# Question

Access object created by another thread without invoking every time?

I have a simple status label that I update frequently during a long running routine. The routine is on a timer and thus on another thread, so I get the

Cross-thread operation not valid
error. I found a fix on SO, which looks like this:

lblQuery1Status.Invoke(new Action(delegate
{
lblQuery1Status.Text = "Status: Publishing";
}));


However, I update the text of this control 7 or 8 times during the routine. Is there a more efficient or simple way to do this?

Answer

If you want to "simplify" the syntax, you can always use an inline lambda to "shorten" the syntax:

lblQuery1Status.Invoke(new Action(() => lblQuery1Status.Text = "Status: Publishing"));

You can also create an action variable for the invoke and re-invoke the action whenever needed:

Action updateStatus = () => 
    lblQuery1Status.Invoke(new Action(() => lblQuery1Status.Text = "Status: Publishing"));

You can then invoke it as a method as many times as needed:

updateStatus();