gpt4 book ai didi

c# - worker 线程可以在GUI中读取控件吗?

转载 作者:行者123 更新时间:2023-12-03 13:22:22 24 4
gpt4 key购买 nike

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

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

我正在使用WPF C#

最佳答案

简而言之,没有。控件只能由创建它们的线程访问。

亲自证明:

<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);
}
}

关于c# - worker 线程可以在GUI中读取控件吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3295870/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com