在WinForm中使用WPF MVVM模式 线程更新ObservableCollection报错
使用在WPF的思路尝试
1. 使用Application.Current.Dispatcher.Invoke时,会报Application.Current=null
2. 新建Application.Current后,由于调度线程不同报错,使用这种方法貌似行不通
使用WinForm的同步上下文解决了问题,下面是封装过的SafeObservableCollection(来自ChatGPT)
public class SafeObservableCollection<T> : ObservableCollection<T>
{
private SynchronizationContext syncContext;
public SafeObservableCollection()
{
syncContext = SynchronizationContext.Current;
}
public SafeObservableCollection(IEnumerable<T> collection) : base(collection)
{
}
protected override void OnCollectionChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
if(syncContext == null)
{
syncContext = SynchronizationContext.Current;
}
if (syncContext != null)
{
syncContext.Send(new SendOrPostCallback(_ => base.OnCollectionChanged(e)), null);
}
else
{
// Handle the case when there is no SynchronizationContext available
// You can choose to log, throw an exception, or simply ignore the notification.
// For this example, we'll just log the message to the console.
Console.WriteLine("Notification skipped: No SynchronizationContext available.");
}
}
}
使用时可以直接在线程对SafeObservableCollection进行操作
PlayList.RemoveAt(0);