你可以从另一个线程访问UI元素? (得到未设置) [英] Can you access UI elements from another thread? (get not set)
问题描述
我看到了很多关于谷歌的线程/这里从另一个线程更新UI元素。
I see a lot of threads on google/here on UPDATING a UI element from another thread.
如果我只想得到一个复选框的值是什么?
What if I want to just get the value of a checkbox?
我是能够做到这一点,而不必做什么特别?
Am I able to do this without having to do anything special?
推荐答案
修改:看来我要收回我之前写的。试过如下:
Edit: It seems I have to take back what I wrote before. Tried the following:
增加了一个名为文本框 myTextBox
并试图检索文本
属性的值:
Added a textbox called myTextBox
and tried to retrieve the value of the Text
property:
Thread t = new Thread(
o =>
{
Thread.Sleep(2000);
string value = myTextBox.Text;
Thread.Sleep(2000);
});
t.Start();
和似乎在应用程序(WPF)2秒钟后崩溃。使用调度工作:
And it seems that the app (WPF) crashes after 2 seconds. Using the dispatcher works:
Thread t = new Thread(
o =>
{
Thread.Sleep(2000);
myTextBox.Dispatcher.BeginInvoke(
(Action)(() => { string value = myTextBox.Text; }));
Thread.Sleep(2000);
});
t.Start();
因此,你仍然需要从GUI组件,至少在WPF读值时,要经过调度线程。
二修改:这变得更好。显然,重复经典的WinForms实验表明,它的作品读文本
属性,而不使用调用/的BeginInvoke
。有趣的是,似乎还设置属性工作正常(无调用),虽然我敢打赌它不是线程安全和应用程序不抱怨的某些原因。
Second edit: This gets better. Apparently repeating the experiment for classic WinForms reveals that it works to read the Text
property without using Invoke/BeginInvoke
. Interestingly enough, it seems that also setting the property works fine (without invoke), although I'll wager it's not thread safe and the app doesn't complain for some reason.
底线:这是在任何情况下与其他线程的GUI组件进行交互时使用的调度是一个好主意,因为它确保了读/写操作序列化到一个单独的线程,所以你有没有线程安全问题。
Bottom line: It's a good idea in any case to use the dispatcher when interacting with GUI components from other threads, as it ensures the reads/writes are serialized to a single thread and so you have no thread-safety issues.
这篇关于你可以从另一个线程访问UI元素? (得到未设置)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!