为什么要在这里使用的BeginInvoke? [英] Why use BeginInvoke here?

查看:102
本文介绍了为什么要在这里使用的BeginInvoke?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我期待到别人的code和没有太多的经验,任何与多线程。我碰到这条线code:

I am looking into someone else's code and do not have much experience with anything to do with multi-threading. I came across this line of code:

的BeginInvoke((MethodInvoker)委托(){btnCalibrate.PerformClick();});

我不知道为什么这样做时,只是这会起作用: btnCalibrate.PerformClick();

I was wondering why do this when just this would have worked: btnCalibrate.PerformClick();

谢谢您的回答。

推荐答案

因为如果code跑在从创建GUI中的按钮,一个不同的线程,一个异常将被抛出。后台线程不能直接调用的GUI方法,因为GUI不是线程安全的。

Because if this code ran in a different thread from the one that created the button in the GUI, an exception would be thrown. Background threads cannot directly call methods on the GUI because the GUI is not thread safe.

当然,这仅仅是个合理的理由使用的BeginInvoke !但是,不难发现code包含咒语或刚刚投入没有很好的理由魔法,因为笔者已经看到另一个例子,做了这种方式,因此认为它必须有必要在所有的情况下, 。如果code,你正在使用是单线程的,则是不必要​​的。

Of course, this is just the rational reason for using BeginInvoke! But it is not unusual to find code that contains incantations or magic spells that have just been put in for no good reason, because the author had seen another example that did it that way and so assumed it must be necessary in all cases. If the code you're working with is single threaded, then it is unnecessary.

在特别是Windows窗体本身是坚决单线程的。在所有的Windows和控制所有的操作都​​发生在同一个线程,和他们所有的事件触发该同一线程。使用一个GUI线程的划分通过一个连续运行的线程上和从队列中读取消息消息循环。的BeginInvoke的目的是最终发布消息到该队列,有效地说:当你有一个时刻,请运行该块的code。

In particular, Windows Forms itself is resolutely single-threaded. All operations on all windows and controls happen on the same thread, and all their events fire on that same thread. The use of the one GUI thread is partitioned out through a message loop that continuously runs on the thread and reads messages from a queue. The purpose of BeginInvoke is ultimately to post a message to that queue, effectively saying "When you have a moment, please run this chunk of code."

这篇关于为什么要在这里使用的BeginInvoke?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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