Click here to Skip to main content
15,894,343 members
Articles / Desktop Programming / Windows Forms

Avoiding InvokeRequired

Rate me:
Please Sign up or sign in to vote.
4.83/5 (138 votes)
28 Jun 2012CPOL12 min read 497.1K   3.2K   245  
How to avoid asking if InvokeRequired has the minimum code and no copy/paste
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;


namespace UIThread20Compact
{
    static class ControlExtensions
    {
        /// <summary>
        /// Runs code in UI thread synchronously with BeginInvoke when required.
        /// </summary>
        /// <param name="code">the code, like "delegate { this.Text = "new text"; }"
        /// </param>
        static public void UIThread(this Control control, Action code)
        {
            if (control.InvokeRequired)
            {
                control.BeginInvoke(code);
                return;
            }
            code.Invoke();
        }

        /// <summary>
        /// Runs code in UI thread synchronously with Invoke when required.
        /// </summary>
        /// <param name="code">the code, like "delegate { this.Text = "new text"; }"
        /// </param>
        static public void UIThreadInvoke(this Control control, Action code)
        {
            if (control.InvokeRequired)
            {
                control.Invoke(code);
                return;
            }
            code.Invoke();
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

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


Written By
Software Developer (Senior) TheWarrantyGroup
Argentina Argentina
I'm a Java/C# developer, with (some) experience in mobile and web development. I enjoy learning useful (and useless) stuff to be a better developer. I like to share the (little amount of) knowledge I have, by creating libraries and utility classes. CodeProject rocks! I wonder why the Java part is not so popular...

Comments and Discussions