這是一個小型測驗應用程式,可嘗試從我的主應用程式中解決此問題。我先貼一下代碼。
XAML:
<Window
x:Class="ThreadTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:ThreadTest"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Border BorderBrush="Black" BorderThickness="2" Grid.Row="0"/>
<StackPanel Orientation="Vertical" HorizontalAlignment="Center" VerticalAlignment="Center" Grid.Row="0">
<Button Click="{x:Bind ViewModel.AddPosition}" Content="Add To List" Margin="5"/>
<TextBlock Text="{x:Bind ViewModel.OutputString, Mode=OneWay}" Margin="5"/>
<ListView ItemsSource="{x:Bind ViewModel.PositionCollection, Mode=OneWay}" Margin="5">
<ListView.HeaderTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Border BorderBrush="BlueViolet" BorderThickness="0,0,0,1">
<TextBlock Text="ID" Margin="5,0,0,0" FontWeight="Bold"/>
</Border>
<Border Grid.Column="1" BorderBrush="BlueViolet" BorderThickness="0,0,0,1">
<TextBlock Text="Place" Margin="5,0,0,0" FontWeight="Bold"/>
</Border>
</Grid>
</DataTemplate>
</ListView.HeaderTemplate>
<ListView.ItemTemplate>
<DataTemplate x:DataType="local:PositionModel">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Text="{x:Bind Path=ID, Mode=OneWay}"/>
<TextBlock Grid.Column="1" Text="{x:Bind Path=Place, Mode=OneWay}" />
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackPanel>
</Grid>
</Window>
視圖模型(MainViewModel.cs):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using Microsoft.UI.Dispatching;
using Windows.UI.Core;
using Windows.ApplicationModel;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace ThreadTest {
public class MainViewModel : BindableBase, INotifyPropertyChanged {
private String outputString = "Empty";
public MainViewModel() {
}
public String OutputString {
get { return outputString; }
set { SetProperty(ref outputString, value); }
}
private Random _random = new Random();
private int _id = 0;
private ObservableCollection<PositionModel> _positioncollection = new();
public ObservableCollection<PositionModel> PositionCollection {
get { return _positioncollection; }
set { SetProperty(ref _positioncollection, value); }
}
public async void AddPosition() {
Progress<PositionModel> progress = new();
progress.ProgressChanged = Progress_ProgressChanged;
// Increase id for each new position added.
_id ;
// Setup/
var _position = new PositionModel {
ID = _id,
Place = _random.Next(1, 1000), // Get a random starting point.
};
PositionCollection.Add(_position);
PositionsClass positionsClass = new(ref _position, progress);
await Task.Run(() => { positionsClass.Start(); });
}
private void Progress_ProgressChanged(object sender, PositionModel e) {
// This is so I can see that the thread is actually running.
OutputString = Convert.ToString(e.Place);
}
}
}
BindableBase.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace ThreadTest {
public class BindableBase : INotifyPropertyChanged {
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = null) {
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
protected bool SetProperty<T>(ref T originalValue, T newValue, [CallerMemberName] string propertyName = null) {
if (Equals(originalValue, newValue)) {
return false;
}
originalValue = newValue;
OnPropertyChanged(propertyName);
return true;
}
}
}
PositionModel.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace ThreadTest {
public class PositionModel {
/*
//Impliment INotifyPropertyChanged up above if using this.
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = null) {
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
protected bool SetProperty<T>(ref T originalValue, T newValue, [CallerMemberName] string propertyName = null) {
if (Equals(originalValue, newValue)) {
return false;
}
originalValue = newValue;
OnPropertyChanged(propertyName);
return true;
}
private int _id = 0;
public int ID {
get { return _id; }
set { SetProperty(ref _id, value); }
}
private int _place = 0;
public int Place {
get { return _place; }
set { SetProperty(ref _place, value); }
}
*/
public int ID { get; set; }
public int Place { get; set; }
}
}
PositionsClass.cs:
using Microsoft.UI.Dispatching;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ThreadTest {
public class PositionsClass {
private IProgress<PositionModel> _progress;
private PositionModel _position;
public PositionsClass(ref PositionModel position, IProgress<PositionModel> progress) {
_progress = progress;
_position = position;
}
public void Start() {
StartFakePosition();
}
private void StartFakePosition() {
// Just using a quick loop to keep the numbers going up.
while (true) {
_position.Place ;
// Send position back.
_progress.Report(_position);
Thread.Sleep(100);
}
}
}
}
因此,基本上您將單擊“添加到串列”按鈕,然后該按鈕將創建 PositionsClass 位置類,創建并填充 PositionModel _position,創建 ObservableCollection PositionCollection(系結到 xaml 上的 listview)然后將該類分離到它自己的執行緒中。該類將獲取 _position 并增加其 .Place,然后將 progress.report _position 報告回主執行緒。
Now I'm trying to figure out how to get the PositionCollection (of ObservableCollection) to update the lisview ui. I subscribed to progress.ProgressChanged and update the OutputString just to make sure the class is actually running and incrementing which does work.
I've tried various things I've found on the web, including different inherited ObversableCollection methods, none of which work or I missunderstood them.
I thought implementing an INotifyPropertyChange on PositionModel.cs itself would work (the commented out code), but doing so brings up a cross thread error. I imagine it's because positionsClass on a seperate thread is updating .Place which is causing the cross thread error?
Can anyone help explain how to get the ObservableCollection to update the ui when it's property changes in my example above? Thanks! In my main app, I'll be updating a lot of properties on a separate thread, rather than just the 2 in this example. Which is why I thought it'd be easier to just send the whole model back in a progress.report.
uj5u.com熱心網友回復:
我想我已經想通了。首先,我在上面的 PositionModel.cs 代碼(注釋掉的部分)上啟用 INotifyProperty。然后我補充說:
private readonly DispatcherQueue _dispatcherQueue = DispatcherQueue.GetForCurrentThread();
public CoreDispatcher Dispatcher { get; }
到 MainViewModel,并將 AddPosition 修改為:
public async void AddPositionDispatcher() {
// Increase id for each new position added.
_id ;
// Setup/
var _position = new PositionModel {
ID = _id,
Place = _random.Next(1, 1000), // Get a random starting point.
};
PositionCollection.Add(_position);
PositionsClassDispatcher positionsClassDispatcher = new(_position, _dispatcherQueue);
await Task.Run(() => { positionsClassDispatcher.Start(); });
}
我將 DispatcherQueue 發送到新修改的 PositionsClassDispatcher.cs:
using Microsoft.UI.Dispatching;
using System.Threading;
namespace ThreadTest {
internal class PositionsClassDispatcher {
private PositionModel _position;
DispatcherQueue _queue;
public PositionsClassDispatcher(PositionModel position, DispatcherQueue dispatcherQueue) {
_queue = dispatcherQueue;
_position = position;
}
public void Start() {
StartFakePosition();
}
private void StartFakePosition() {
// Just using a quick loop to keep the numbers going up.
while (true) {
_queue.TryEnqueue(() => {
_position.Place ;
});
Thread.Sleep(100);
}
}
}
}
這將采用 DispatcherQueue 并使用 TryEnqueue 更新 _position.Place。ObvservableCollection 現在可以在更新屬性時正確更新 UI。還要更新 XAML 以使用新的 AddPositionDispatcher()。
此外,由于 WinUI3 似乎不再具有 Dispatcher,因此不得不使用 DispatcherQueue 而不是 Dispatcher。
Window.Dispatcher 屬性
Window.Dispatcher 可能會在將來的版本中更改或不可用。請改用 Window.DispatcherQueue。
Which has caused quite a few problems trying to figure this problem out, as a lot of info out there is based on Dispatcher rather than DispatcherQueue.
Hope this helps anyone else that runs into the problem.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/444726.html
標籤:c# .net multithreading observablecollection winui-3
上一篇:使用共享記憶體的執行緒
