Click here to Skip to main content
15,867,879 members
Articles / Desktop Programming / Windows Forms

Getting Around InvokeRequired Without Copy and Paste

Rate me:
Please Sign up or sign in to vote.
4.93/5 (14 votes)
17 Aug 20072 min read 119K   749   53  
Instead of copying and pasting the same if(InvokeRequired) logic in every multithreaded function, use attributes to make code cleaner, its centralize logic and make it self documenting.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using Osherove.SimpleInterception.AOPAttributes;

namespace ThreadSafeUI
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        protected override void OnActivated(EventArgs e)
        {
            base.OnActivated(e);
        }

        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);
        }

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            base.OnFormClosing(e);
        }

        [CustomLogging]
        protected virtual void button1_Click(object sender, EventArgs e)
        {
            Thread test = new Thread(new  ThreadStart(DoSomrthing));
            test.Start();
        }

        [RunInUIThread]
        protected virtual void DoSomrthing()
        {
            button1.Text = "hey";
        }
    }
}

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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
United States United States
I've been a software developer since 1996 and have enjoyed C# since 2003. I have a Bachelor's degree in Computer Science and for some reason, a Master's degree in Business Administration. I currently do software development contracting/consulting.

Comments and Discussions