是否有可能从另一个线程访问UI元素,如果线程没有修改的元素? [英] Is it possible to access a UI element from another thread if the thread doesn't modify that element?

查看:220
本文介绍了是否有可能从另一个线程访问UI元素,如果线程没有修改的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们假设在该实例化的形式/控制/元件(通常是主线程)不修改/在同一时间访问该元素的线程中运行的代码,是有可能:

Let's assume that the code running in the thread that instantiated the form/control/element (usually the main thread) does not modify/access that element at the same time, is it possible to:


  1. 得到一个TextBox的Text属性。

  1. get the Text property of a TextBox.

列举一个ListView。

enumerate a ListView.

订阅窗体的Closing事件。 (明知钩将从实例化表单中的线程调用)

subscribe to a Form's Closing event. (Knowing that the hook will be called from the thread that instantiated that form)

我已经尝试了所有3,程序似乎并不抱怨。我一直以为你不得不调用一个希望,甚至远程碰任何东西的用户界面相关的(读或写)的任何电话。

I have tried all 3 and the program doesn't seem to complain about it. I had always thought that you had to invoke any call that wants to even remotely touch anything UI related (read or write).

我非常清楚我为什么需要使用修改IsInvokeRequired /调用模式当一个元素,但我不明白为什么访问属性/事件会引起任何问题。

I understand very clearly why I need to use the IsInvokeRequired/Invoke pattern when modifying an element, but I cannot see why accessing properties/events would cause any problems.

推荐答案

这是绝对有可能,但是,它可能会导致意外的行为。此外,其他的线程相关的错误也需要考虑到例如竞争条件/死锁看到托管线程处理的最佳Practises

It's definitely possible, however, it could lead to unexpected behaviour. Also, other thread-related bugs also need to be taken into consideration e.g. race conditions/deadlocks see Managed Threading Best Practises.

我会始终坚持访问UI线程的UI是在安全方面。

I would always stick to accessing the UI on the UI thread to be on the safe side.

这篇关于是否有可能从另一个线程访问UI元素,如果线程没有修改的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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