开发者

Why doesn't the compiler (or the runtime) do the InvokeRequired pattern for me?

开发者 https://www.devze.com 2023-03-20 05:52 出处:网络
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(

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.


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");

0

精彩评论

暂无评论...
验证码 换一张
取 消