210

I have become painfully aware of just how often one needs to write the following code pattern in event-driven GUI code, where

private void DoGUISwitch() {
    // cruisin for a bruisin' through exception city
    object1.Visible = true;
    object2.Visible = false;
}

becomes:

private void DoGUISwitch() {
    if (object1.InvokeRequired) {
        object1.Invoke(new MethodInvoker(() => { DoGUISwitch(); }));
    } else {
        object1.Visible = true;
        object2.Visible = false;
    }
}

This is an awkward pattern in C#, both to remember, and to type. Has anyone come up with some sort of shortcut or construct that automates this to a degree? It'd be cool if there was a way to attach a function to objects that does this check without having to go through all this extra work, like a object1.InvokeIfNecessary.visible = true type shortcut.

Previous answers have discussed the impracticality of just calling Invoke() every time, and even then the Invoke() syntax is both inefficient and still awkward to deal with.

So, has anyone figured out any shortcuts?

5
  • 2
    I've wondered the same thing, but in regards to WPF's Dispatcher.CheckAccess(). Commented Mar 2, 2010 at 23:35
  • I thought up a rather crazy suggestion inspired by your object1.InvokeIfNecessary.Visible = true line; check out my updated answer and let me know what you think. Commented Mar 3, 2010 at 0:05
  • 1
    Add a Snippet to help implement method suggested by Matt Davis: see my answer (late but just showing how for later readers ;-) ) Commented Feb 15, 2011 at 13:40
  • 3
    I don't understand why Microsoft did nothing to simplify that in .NET. Creating delegates for each change on form from thread is really annoying. Commented Oct 15, 2012 at 17:26
  • @Kamil I couldn't agree more! This is such an oversight, given its ubiquity. Within the framework, just handle the threading if necessary. Seems obvious. Commented Feb 20, 2019 at 21:22

9 Answers 9

163

Lee's approach can be simplified further

public static void InvokeIfRequired(this Control control, MethodInvoker action)
{
    // See Update 2 for edits Mike de Klerk suggests to insert here.

    if (control.InvokeRequired) {
        control.Invoke(action);
    } else {
        action();
    }
}

And can be called like this

richEditControl1.InvokeIfRequired(() =>
{
    // Do anything you want with the control here
    richEditControl1.RtfText = value;
    RtfHelpers.AddMissingStyles(richEditControl1);
});

There is no need to pass the control as parameter to the delegate. C# automatically creates a closure.

If you must return a value, you can use this implementation:

private static T InvokeIfRequiredReturn<T>(this Control control, Func<T> function)
{
    if (control.InvokeRequired) {
        return (T)control.Invoke(function);
    } else {
        return function();
    }
}

UPDATE:

According to several other posters Control can be generalized as ISynchronizeInvoke:

public static void InvokeIfRequired(this ISynchronizeInvoke obj,
                                         MethodInvoker action)
{
    if (obj.InvokeRequired) {
        obj.Invoke(action, null);
    } else {
        action();
    }
}

DonBoitnott pointed out that unlike Control the ISynchronizeInvoke interface requires an object array for the Invoke method as parameter list for the action.

According to the ISynchronizeInvoke.Invoke(Delegate, Object[]) Method documentation we can pass null if no arguments are needed.


UPDATE 2

Edits suggested by Mike de Klerk (see comment in 1st code snippet for insert point):

// When the form, thus the control, isn't visible yet, InvokeRequired  returns false,
// resulting still in a cross-thread exception.
while (!control.Visible)
{
    System.Threading.Thread.Sleep(50);
}

See ToolmakerSteve's and nawfal's comments below for concerns about this suggestion.

Sign up to request clarification or add additional context in comments.

18 Comments

Wouldn't be better to have ISynchronizeInvoke instead of Control? (Kudos to Jon Skeet stackoverflow.com/questions/711408/…)
@mike-de-clerk, I am concerned about your suggestion to add while (!control.Visible) ..sleep... To me that has a bad code smell, as it is a potentially unbounded delay (maybe even an infinite loop in some cases), in code that may have callers who are not expecting such a delay (or even a deadlock). IMHO, any use of Sleep should be the responsibility of each caller, OR should be in a separate wrapper that is clearly marked as to its consequences. IMHO, usually it would be better to "fail hard" (exception, to catch during testing), or to "do nothing" if the control is not ready. Comments?
The while (!Visible) needs a timeout. Bad practice that could lead to an infinite loop that would be difficult to debug.
It does not, because we are invoking on winforms controls anyway. See also learn.microsoft.com/en-us/dotnet/api/…
@OlivierJacot-Descombes, your assumption for Update 2 is incorrect I think (besides the blocking Thread.Sleep calls). You say When the form, thus the control, isn't visible yet, InvokeRequired returns false, resulting still in a cross-thread exception., but how plausible is this? If the window handle is not created for the control, wouldn't updating the control in a different thread anyway work? At that point its just setting values to an in-memory object. This is why the common if (c.InvokeRequired) c.Invoke(foo); else foo(); pattern works so well.
|
143

You could write an extension method:

public static void InvokeIfRequired(this Control c, Action<Control> action)
{
    if(c.InvokeRequired)
    {
        c.Invoke(new Action(() => action(c)));
    }
    else
    {
        action(c);
    }
}

And use it like this:

object1.InvokeIfRequired(c => { c.Visible = true; });

EDIT: As Simpzon points out in the comments you could also change the signature to:

public static void InvokeIfRequired<T>(this T c, Action<T> action) 
    where T : Control

7 Comments

Maybe i'm just too dumb, but this code won't compile. So i fixed it as it built by me (VS2008).
Just for completeness: In WPF there is a different dispatching mechanism, but it works rather analogous. You could use this extension method there: public static void InvokeIfRequired<T>(this T aTarget, Action<T> aActionToExecute) where T:DispatcherObject { if (aTarget.CheckAccess()) { aActionToExecute(aTarget); } else { aTarget.Dispatcher.Invoke(aActionToExecute); } }
I added an answer that simplifies Lee's solution slightly.
Hi, as I where using something similiar, there can be be a big problem coming from this generic implementation. If the Control is Disposing/Disposed, you will get a ObjectDisposedException.
@Offler - Well if they're being disposed on a different thread you have a synchronisation problem, it's not an issue in this method.
|
42

Here's the form I've been using in all my code.

private void DoGUISwitch()
{ 
    Invoke( ( MethodInvoker ) delegate {
        object1.Visible = true;
        object2.Visible = false;
    });
} 

I've based this on the blog entry here. I have not had this approach fail me, so I see no reason to complicate my code with a check of the InvokeRequired property.

Hope this helps.

3 Comments

+1 - I stumbled on the the same blog entry you did, and think this is the cleanest approach of any proposed
There is a small performance hit using this approach, which could pile up when called multiple times. stackoverflow.com/a/747218/724944
You have to use InvokeRequired if the code could be executed before the control was shown or you will have a fatal exception.
12

Here's an improved/combined version of Lee's, Oliver's and Stephan's answers.

public delegate void InvokeIfRequiredDelegate<T>(T obj)
    where T : ISynchronizeInvoke;

public static void InvokeIfRequired<T>(this T obj, InvokeIfRequiredDelegate<T> action)
    where T : ISynchronizeInvoke
{
    if (obj.InvokeRequired)
    {
        obj.Invoke(action, new object[] { obj });
    }
    else
    {
        action(obj);
    }
} 

The template allows for flexible and cast-less code which is much more readable while the dedicated delegate provides efficiency.

progressBar1.InvokeIfRequired(o => 
{
    o.Style = ProgressBarStyle.Marquee;
    o.MarqueeAnimationSpeed = 40;
});

Comments

10

Create a ThreadSafeInvoke.snippet file, and then you can just select the update statements, right click and select 'Surround With...' or Ctrl-K+S:

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippet Format="1.0.0" xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <Header>
    <Title>ThreadsafeInvoke</Title>
    <Shortcut></Shortcut>
    <Description>Wraps code in an anonymous method passed to Invoke for Thread safety.</Description>
    <SnippetTypes>
      <SnippetType>SurroundsWith</SnippetType>
    </SnippetTypes>
  </Header>
  <Snippet>
    <Code Language="CSharp">
      <![CDATA[
      Invoke( (MethodInvoker) delegate
      {
          $selected$
      });      
      ]]>
    </Code>
  </Snippet>
</CodeSnippet>

Comments

7

I'd rather use a single instance of a method Delegate instead of creating a new instance every time. In my case i used to show progress and (info/error) messages from a Backroundworker copying and casting large data from a sql instance. Everywhile after about 70000 progress and message calls my form stopped working and showing new messages. This didn't occure when i started using a single global instance delegate.

delegate void ShowMessageCallback(string message);

private void Form1_Load(object sender, EventArgs e)
{
    ShowMessageCallback showMessageDelegate = new ShowMessageCallback(ShowMessage);
}

private void ShowMessage(string message)
{
    if (this.InvokeRequired)
        this.Invoke(showMessageDelegate, message);
    else
        labelMessage.Text = message;           
}

void Message_OnMessage(object sender, Utilities.Message.MessageEventArgs e)
{
    ShowMessage(e.Message);
}

Comments

7

Usage:

control.InvokeIfRequired(c => c.Visible = false);

return control.InvokeIfRequired(c => {
    c.Visible = value

    return c.Visible;
});

Code:

using System;
using System.ComponentModel;

namespace Extensions
{
    public static class SynchronizeInvokeExtensions
    {
        public static void InvokeIfRequired<T>(this T obj, Action<T> action)
            where T : ISynchronizeInvoke
        {
            if (obj.InvokeRequired)
            {
                obj.Invoke(action, new object[] { obj });
            }
            else
            {
                action(obj);
            }
        }

        public static TOut InvokeIfRequired<TIn, TOut>(this TIn obj, Func<TIn, TOut> func) 
            where TIn : ISynchronizeInvoke
        {
            return obj.InvokeRequired
                ? (TOut)obj.Invoke(func, new object[] { obj })
                : func(obj);
        }
    }
}

Comments

3

I Kind of like to do it a bit different, i like to call "myself" if needed with an Action,

    private void AddRowToListView(ScannerRow row, bool suspend)
    {
        if (IsFormClosing)
            return;

        if (this.InvokeRequired)
        {
            var A = new Action(() => AddRowToListView(row, suspend));
            this.Invoke(A);
            return;
        }
         //as of here the Code is thread-safe

this is a handy pattern, the IsFormClosing is a field that i set to True when I am closing my form as there might be some background threads that are still running...

Comments

-4

You should never be writing code that looks like this:

private void DoGUISwitch() {
    if (object1.InvokeRequired) {
        object1.Invoke(new MethodInvoker(() => { DoGUISwitch(); }));
    } else {
        object1.Visible = true;
        object2.Visible = false;
    }
}

If you do have code that looks like this then your application is not thread-safe. It means that you have code which is already calling DoGUISwitch() from a different thread. It's too late to be checking to see if it's in a different thread. InvokeRequire must be called BEFORE you make a call to DoGUISwitch. You should not access any method or property from a different thread.

Reference: Control.InvokeRequired Property where you can read the following:

In addition to the InvokeRequired property, there are four methods on a control that are thread safe to call: Invoke, BeginInvoke, EndInvoke and CreateGraphics if the handle for the control has already been created.

In a single CPU architecture there's no problem, but in a multi-CPU architecture you can cause part of the UI thread to be assigned to the processor where the calling code was running...and if that processor is different from where the UI thread was running then when the calling thread ends Windows will think that the UI thread has ended and will kill the application process i.e. your application will exit without error.

3 Comments

Hey there, thanks for your answer. It's been years since I asked this question (and almost just as long a time since I've worked with C#), but I was wondering if you could explain a bit further? The docs you linked to refer to a specific danger of calling invoke() et al before the control is given a handle, but IMHO doesn't describe what you've described. The whole point of all this invoke() nonsense is to update the UI in a thread-safe manner, and I would think putting more instructions in a blocking context would lead to stuttering? (Ugh...glad I stopped using M$ tech. So complicated!)
I also want to note that despite frequent use of the original code (way back when), I did not observe the problem you described on my dual-CPU desktop
I doubt this answer is accurate as MSDN shows plenty of examples just like the OP gave.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.