Wpf中ViewModel類裡面經常會需要用到ObservableCollection來管理清單資料,在做異步通信的時候也會碰到“不支援從排程程式線程以外的線程對其 SourceCollection 進行的更改”這樣的異常,解決方法如下
ThreadPool.QueueUserWorkItem(delegate
{
System.Threading.SynchronizationContext.SetSynchronizationContext(new
System.Windows.Threading.DispatcherSynchronizationContext(System.Windows.Application.Current.Dispatcher));
System.Threading.SynchronizationContext.Current.Post(pl =>
{
//裡面寫真正的業務内容
}, null);
});