在我的程序中,我通过使用 this answer 中使用的 AddOnUI 扩展方法从后台工作线程将对象添加到 ObservableCollection .
我使用的扩展方法:
public static void AddOnUI<T>(this ICollection<T> collection, T item)
{
Action<T> addMethod = collection.Add;
Application.Current.Dispatcher.BeginInvoke( addMethod, item );
}
...
collection.AddOnUI(new B());
此解决方案非常适用于从后台工作线程添加的集合对象。但是,当仅在不涉及后台线程的 UI 线程上手动添加集合对象时,集合不会填充数据或 View 。从 ObservableCollection 调用 add 方法时,有没有办法查询哪个线程处于事件状态?
也许做这样的事情?:
if(calling from background thread)
collection.AddOnUI(new B());
else //Manually adding from UI Thread
collection.Add(new B());
解决方案:
我的解决方案最终与我非常喜欢的伪代码非常相似。
if(System.Threading.Thread.CurrentThread.IsBackground)
collection.AddOnUI(new B());
else //Manually adding from UI Thread
collection.Add(new B());
替代解决方案:
AddOnUI()(将 BeginInvoke 更改为 Invoke):
public static void AddOnUI<T>(this ICollection<T> collection, T item)
{
Action<T> addMethod = collection.Add;
Application.Current.Dispatcher.Invoke(addMethod, item);
}
collection.AddOnUI(new B());
请您参考如下方法:
System.Threading.Thread.CurrentThread告诉你你在哪个线程,它可以与 Dispatcher.Thread 进行比较属性(property)。
