A short way to invoke methods in C#

By | December 26, 2010

The code example shows how to invoke methods with one-line call. It does not require writing explicit delegates, works in .NET 2.0 and later by accessing outer variables (text in the example) from an anonymous method. Invoke() method can be used instead of BeginInvoke().

C# code:

// Control method
public void SetText(string text)
{
    if (this.InvokeRequired)
    {
        // Invoke method
        BeginInvoke( new MethodInvoker( delegate() { SetText(text); } ) );
    }
    else
    {
        // actual code
        this.Text = text
    }
}

Leave a Reply

Your email address will not be published.