Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#4.0

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

4.81/5 (29 votes)
21 Aug 2010CPOL 1  
How to access a control from a different thread + good alternatives by other members!

Added: This article[^] has some interesting stuff about potential bugs with InvokeRequired - worth a read!


This comes up time and again.
Luc[^] has a great article explaining all here[^].


For those just wanting the solution...



C#
public void WithParameterMethod(int parameter)
{
    if (InvokeRequired)
        Invoke(new MethodInvoker(
            delegate
            {
                // Call your method again
                WithParameterMethod(parameter);
            }
            ));
    else
    {
        // Do your thing here!
    }
}


C#
public void NoParameterMethod()
{
    if (InvokeRequired)
        Invoke(new MethodInvoker(
            // Call your method again
            NoParameterMethod
            ));
    else
    {
        // Do your thing here!
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)