65.9K
CodeProject is changing. Read more.
Home

Changing a WinForms Control on the 'UI' Thread from another Thread

starIconstarIconstarIconstarIconstarIcon

5.00/5 (9 votes)

Mar 23, 2010

CPOL
viewsIcon

8600

This version works regardless of parameters:public void AnyMethod(int parameter){ MethodInvoker wrapper = new MethodInvoker(delegate() { // Do your thing here! }); if (this.InvokeRequired) this.Invoke(wrapper); else wrapper();}Note also...

This version works regardless of parameters:
public void AnyMethod(int parameter)
{
    MethodInvoker wrapper = new MethodInvoker(delegate()
    {
        // Do your thing here!
    });
    if (this.InvokeRequired)
        this.Invoke(wrapper);
    else
        wrapper();
}
Note also that it does not need to be wrapped in a method to work. You can just place it inline. Any required variables will be captured by the delegate.
int parameter = 5;
MethodInvoker wrapper = new MethodInvoker(delegate()
{
    // Do your thing here! For example:
    lblCount.Text = parameter.ToString();
});
if (this.InvokeRequired)
    this.Invoke(wrapper);
else
    wrapper();