2

Why isn't cross-thread UI update safety handled automatically?

To ensure thread-safety when potentially updating the UI from another thread we have to write the if (Control.InvokeRequired()) Invoke(..) pattern, or something equivalent. Could the runtime observe when I'm calling a UI-updating method from another thread and marshal the call for me? It must know when this is needed because it throws an exception if you try to do it without the necessary precautions.

Could the compiler just apply the pattern for me on every UI update call? If this would cause unacceptable overhead, perhaps this feature could be controlled by an application attribute (the developer could apply the attribute only when writing a multi-threaded application in which cross-thread UI updates are going to happen).

I can imagine several potential answers: either it's a dumb idea because , or it's impossible/impractical because , or it just isn't seen to add enough value to justify the cost of development.

Igby Largeman
  • 16,495
  • 3
  • 60
  • 86
  • 1
    Because it is a widely abused anti-pattern. It is very rare to write code that can run on *both* the UI thread and a worker thread. InvokeRequired should be used for diagnostics. Because if it returns false when you *know* that the code is running on a worker then there's something seriously wrong. – Hans Passant Jul 13 '11 at 16:01
  • Yes, starting the thread too soon, before Windows has created the window. Or more commonly, forgetting to ensure that the thread has stopped before allowing the window to close. – Hans Passant Jul 13 '11 at 16:07
  • I disagree with Hans here...if you have a long running process, and you want to update the UI to indicate it has finished, how would you do this if you don't spawn off a worker thread? – JoshBerke Jul 13 '11 at 16:10
  • This would add nothing to the language it doesn't already have, and adding features costs more than just the price of developing them. Read Eric Gunnerson's article about why new features start at "-100 points" http://blogs.msdn.com/b/ericgu/archive/2004/01/12/57985.aspx – Dour High Arch Jul 13 '11 at 16:24

1 Answers1

1

I can't answer why although I could ask if this feature is worth the cost of testing, maintenance documentation etc....when you can add a method such as:

    public static void UpdateControl(this Control ctrl, Action<Control> action)
    {
        if (ctrl.InvokeRequired)
        {
            ctrl.Invoke(action,ctrl);


        }
        else
        {
            action(ctrl);

        }

    }

You can then use this like this.textBox.UpdateControl(c=>c.Text="Thread Safe");

JoshBerke
  • 66,142
  • 25
  • 126
  • 164
  • Agreed. There are of course many language features which are considered, but deemed not worthwhile to implement. And if that is the case here, I'd love to have it confirmed (hopefully Eric Lippert or another MS architect will chime in). – Igby Largeman Jul 13 '11 at 16:20