Click here to Skip to main content
15,894,017 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 497K   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.Linq;
using System.Text;
using System.Windows.Forms;

namespace UIThread
{
    static public class FormExtensions
    {

        //Uncomment next line in windows mobile
        //public delegate void MethodInvoker(); 
        //because is not declared in CF!


        /// <summary>
        /// Runs code in UI thread synchronously.
        /// </summary>
        /// <param name="code">the code, like "delegate { this.Text = "new text"; }"
        /// </param>
        static public void UIThread(this Form form, MethodInvoker code)
        {
            if (form.InvokeRequired)
            {
                form.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