为什么WinForms/WPF控件在内部不使用Invoke? [英] Why don't WinForms/WPF controls use Invoke internally?

查看:65
本文介绍了为什么WinForms/WPF控件在内部不使用Invoke?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解为什么GUI控件具有线程相似性.

I understand why GUI controls have thread affinity.

但是为什么控件不在其方法和属性内部使用调用?

现在,您必须要做类似的事情才能更新 TextBox 的值:

Now you have to do stuff like this just to update TextBox value:

this.Invoke(new MethodInvoker(delegate()
{
    textBox.Text = "newValue";
}

仅使用 textBox.Text ="newValue"; 足以表示相同的逻辑.

While using just textBox.Text = "newValue"; would be enough to represent the same logic.

所有要做的就是从此(伪代码)更改 textBox.Text 逻辑:

All that would have to be done is change textBox.Text logic from this (pseudocode):

public string Text
{
    set
    {
        if(!this.InvokeRequired)
            // do the change logic
        else
            throw new BadThreadException();
    }
}

对此:

public string Text
{
    set
    {
        if(!this.InvokeRequired)
            // do the change logic
        else
            this.Invoke(new MethodInvoker(delegate()
            {
                // do the change logic
            }
    }
}

吸气剂和方法也是如此.

The same goes for getters and methods.

我当然不打算删除 Invoke / BeginInvoke ,我只是在问为什么控件不做必要的事情线程自己切换而不是抛出异常.

I'm certainly not proposing to remove Invoke/BeginInvoke, I'm just asking why the controls don't do the necessary thread switch themselves instead of throwing exception.

推荐答案

我认为API通过这种方式强制开发人员做出明确的决定并避免意外的编程错误.我有几个问题可以立即解决:

I think this way API enforces developers to make explicit decision and avoid unintentional programming mistakes. Here are several problems that I could come up with right away:

1.意外的线程阻塞.如果写入属性,则调用线程将不得不阻塞,直到UI线程处理消息为止.而且,如果调用线程拥有UI线程可能想要获取的资源,您将得到一个难以调试的死锁(调用线程持有资源,并等待直到UI线程处理消息为止; UI线程等待直到释放资源为止)).

1. Unintentional thread blocking. If you write to a property, calling thread will have to block until message is processed by UI thread. And if calling thread owns a resource that UI thread might want to acquire you'll get a deadlock which is hard to debug (Calling thread holds a resource, and wait until message is processed by UI thread; UI thread waits until the resource is released).

2.意外的惊喜.如果我们使写操作隐式异步,则会遇到读者永远不要期望值总是最新的情况.

2. Unexpected surprises. If we would make write operations implicitly asynchronous we run into a situation where reader should never expect values to be always up to date.

3.性能影响.如果您编写了一个密集的算法,它隐式地使用了UI调度,那么最终的性能会很差,而且您可以自由地责怪框架开发人员.毕竟,您编写了应在O(n)中运行的排序,但是由于某种原因,它需要很长时间才能完成.

3. Performance impact. If you write an intensive algorithm which uses UI dispatching implicitly, you end up with really poor performance and you are free to blame framework developers. After all you wrote sorting that should run in O(n), but for some reason it takes ages to complete.

这篇关于为什么WinForms/WPF控件在内部不使用Invoke?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆