65.9K
CodeProject is changing. Read more.
Home

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

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.81/5 (27 votes)

Mar 22, 2010

CPOL
viewsIcon

63214

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...

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