工作者线程可以在GUI中读取控件吗? [英] can a worker thread read a control in the GUI?

查看:60
本文介绍了工作者线程可以在GUI中读取控件吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我每隔几秒钟运行一个线程,从数据库中获取一些数据 但这是基于列表框和几个复选框的选择... 不使用GUI线程就可以读取这些控件的值吗?

I got a thread running every few seconds fetching some data from a db but this is based on the selection on a listbox and on a few checkboxes... can I read the values of these controls without using the GUI thread?

只要其中一个控件发生更改,也会读取数据,但是数据可能会在db中更改 没有警告...因此线程每隔几秒钟运行一次.

The data is also read whenever one of the controls change, but the data might change in db without warning...hence the thread running every few seconds.

我正在使用WPF C#

I'm working with wpf C#

推荐答案

总之,没有.控件只能由创建它们的线程访问.

In short, no. Controls can only be accessed by the thread that created them.

亲自证明:

<Window x:Class="ReadControlsBackground.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow"
        Height="350"
        Width="525">
    <StackPanel>
        <Button x:Name="Start"
                Click="Button_Click"
                Content="Start" />
        <ListBox x:Name="List">
            <ListBoxItem>One</ListBoxItem>
            <ListBoxItem>Two</ListBoxItem>
        </ListBox>
        <CheckBox x:Name="Check" />
    </StackPanel>
</Window>



using System;
using System.Diagnostics;
using System.Threading;
using System.Windows;

namespace ReadControlsBackground {
    /// <summary>
    ///   Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window {
        public MainWindow() {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e) {
            Start.IsEnabled = false;
            var t = new Thread(Poll);
            t.Start();
        }

        private void Poll() {
            while (true) {
                Debug.WriteLine(String.Format("List: {0}", List.SelectedValue));
                Debug.WriteLine(String.Format("Check: {0}", Check.IsChecked));
                Thread.Sleep(5000);
            }
        }
    }
}

改为执行以下操作:

private void Poll() {
    while (true) {
        var selected = (String) Dispatcher.Invoke((Func<String>) (() => (List.SelectedValue ?? "?").ToString()));
        var isChecked = (Boolean?) Dispatcher.Invoke((Func<Boolean?>) (() => Check.IsChecked));
        Debug.WriteLine(String.Format("List: {0}", selected));
        Debug.WriteLine(String.Format("Check: {0}", isChecked));
        Thread.Sleep(5000);
    }
}

这篇关于工作者线程可以在GUI中读取控件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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