Click here to Skip to main content
15,881,172 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 494.5K   3.2K   246  
How to avoid asking if InvokeRequired has the minimum code and no copy/paste
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace UIThread20DesktopHelper
{
    public partial class FormAvoidingInvokeRequired : Form
    {
        public FormAvoidingInvokeRequired()
        {
            InitializeComponent();
        }

        private void MultiParamsUnsafe(string text, int number, DateTime dateTime)
        {
            this.textBoxOut.Text = "string = " + text + Environment.NewLine +
                "number = " + number + Environment.NewLine + "datetime = " + dateTime;
        }

        #region No pattern, will crash if running thread != UI thread

        private void buttonSingleNone_Click(object sender, EventArgs e)
        {
            textBoxOut.Clear();
            SetTextUnsafe();
        }

        private void buttonMultiNone_Click(object sender, EventArgs e)
        {
            textBoxOut.Clear();
            new Thread(new ThreadStart( SetTextUnsafe)).Start();
        }

        private void SetTextUnsafe()
        {            
            try
            {                
                textBoxOut.Text = "No pattern was used. Will fail if multithread";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, ex.GetType().Name, MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
            }
        }

        private void buttonMultiNoneParams_Click(object sender, EventArgs e)
        {
            textBoxOut.Clear();
            new Thread(new ThreadStart(SetTextUnsafeParams)).Start();
        }

        private void SetTextUnsafeParams()
        {
            try
            {
                MultiParamsUnsafe("No pattern was used. Will fail if multithread", 2, DateTime.Now);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, ex.GetType().Name, MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
            } 
        }


        #endregion

        #region Standard pattern

        private void buttonSingleStandard_Click(object sender, EventArgs e)
        {
            textBoxOut.Clear();
            SetTextStandardPattern();
        }


        private void buttonMultiStandard_Click(object sender, EventArgs e)
        {
            textBoxOut.Clear();
            (new Thread(new ThreadStart(SetTextStandardPattern))).Start();
        }

        public delegate void DelegateStandardPattern();
        private void SetTextStandardPattern()
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new DelegateStandardPattern(SetTextStandardPattern));
                return;
            }
            textBoxOut.Text = "Standard pattern was used. It works, but its really awfull";
        }

        private void buttonMultiStandardParams_Click(object sender, EventArgs e)
        {
            textBoxOut.Clear();
            (new Thread(delegate() { SetTextStandardPatternParams("StandardPattern with multiple params", 1, DateTime.Now); })).Start();
        }

        public delegate void DelegateStandardPatternParams(string text, int number, DateTime datetime);

        private void SetTextStandardPatternParams(string text, int number, DateTime datetime)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new DelegateStandardPatternParams(SetTextStandardPatternParams), text, number, datetime);
                return;
            }
            MultiParamsUnsafe(text, number, datetime);
        }


        #endregion

        #region UIThread pattern

        private void SingleUIThread_Click(object sender, EventArgs e)
        {
            textBoxOut.Clear();
            SetTextUIThreadPattern();
        }

        private void buttonMultiUIThread_Click(object sender, EventArgs e)
        {
            textBoxOut.Clear();
            (new Thread(delegate() { SetTextUIThreadPattern(); })).Start();
        }

        private void SetTextUIThreadPattern()
        {
            ControlHelper.UIThread(this, delegate
            {
                textBoxOut.Text = "UIThread pattern was used";
            });
        }  

        private void buttonMultiUIThreadParams_Click(object sender, EventArgs e)
        {
            textBoxOut.Clear();
            (new Thread(delegate() { SetTextUIThreadPatternParams("UIThread pattern with multiple params", 4, DateTime.Now); })).Start();            
        }

        private void SetTextUIThreadPatternParams(string text, int number, DateTime dateTime)
        {
            ControlHelper.UIThread(this, delegate
            {
                MultiParamsUnsafe(text, number, dateTime);
            });
        }






        #endregion









    }
}

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