gpt4 book ai didi

无限循环线程中的 C# MVVM 模式更新 UI?

转载 作者:行者123 更新时间:2023-11-30 23:11:10 25 4
gpt4 key购买 nike

<分区>

我有一个后台线程来监听数据,所以这个死循环来输出数据。

并且,我使用 ObservableCollection 绑定(bind) ListBox 并显示日志。

我尝试使用 Dispather.BeginInvoke,但没有用,它不是实时的。我不知道在 MVVM 中更新 UI。

xaml

<ListBox x:Name="lsb_log" Width="auto" ItemsSource="{Binding DisplayLogs}"/>

代码

private ObservableCollection<string> _displayLogs;
public ObservableCollection<string> DisplayLogs
{
get
{
return _displayLogs;
}
}

public Testpro()
{
_displayLogs = new ObservableCollection<string>();

Task.Run(new Action(outputData));
}

private void outputData()
{
string str = "";
while (true)
{
string newString = GetInfoString();

if (string.IsNullOrWhiteSpace(newString) || str == newString)
continue;

str = newString;

Debug.WriteLine(str);
Application.Current.Dispatcher.BeginInvoke((Action)delegate ()
{
DisplayLogs.Add(str);
});
}
}

*编辑:

GetInfoString 将通过 dll 文件调用。

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