[問題] WPF MVVM 在無窮迴圈的 thread 中更新UI
我有一個一直在 catch 資料的 task
當拿到資料後要馬上在 UI 上更新
使用 MVVM binding 了 ObservableCollection 的物件到 ListBox
xaml:
<ListBox x:Name="lsb_log" Width="auto" ItemsSource="{Binding DisplayLogs}"/>
code:
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);
});
}
}
實際上 Debug.WriteLine 能夠 realtime 的跑出結果
但是 BeginInvoke 直到沒資料的時候才會一次 show 出全部的結果
而且都是最後一個 str 的值
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 220.128.199.139
※ 文章網址: https://www.ptt.cc/bbs/C_Sharp/M.1499231038.A.C11.html
推
07/05 14:15, , 1F
07/05 14:15, 1F
→
07/05 14:20, , 2F
07/05 14:20, 2F
推
07/05 16:07, , 3F
07/05 16:07, 3F
推
07/05 18:57, , 4F
07/05 18:57, 4F
推
07/06 17:29, , 5F
07/06 17:29, 5F
推
07/06 18:05, , 6F
07/06 18:05, 6F