我有一段类似于这样的WPF代码。
public class AlphaProductesVM : BaseModel
{
private ObservableCollection<Alphabetical_list_of_product> _NwCustomers;
private int i = 0;
public AlphaProductesVM ()
{
_NwCustomers = new ObservableCollection<Alphabetical_list_of_product>();
var repository = new NorthwindRepository();
repository
.GetAllProducts()
.ObserveOn(SynchronizationContext.Current)
.Subscribe(AddElement);
}
public void AddElements(IEnumerable<Alphabetical_list_of_product> elements)
{
foreach (var alphabeticalListOfProduct in elements)
{
AddElement(alphabeticalListOfProduct);
}
}
public ObservableCollection<Alphabetical_list_of_product> NwCustomers
{
get { return _NwCustomers; }
set { _NwCustomers = value; }
}}
我使用Unity解决上述问题的AlphaProductesVM
。当使用PRISM和UnityBootstrapper发现模块时,即时执行。在运行时,.ObserveOn(SynchronizationContext.Current)
会触发异常,而SynchronizationContext.Current
则具有空值null
。
SetSynchronizationContext
函数调用仅为运行线程设置SynchronizationContext
。这意味着您提到的第二个选项“在主线程中分配”不会影响其他线程。(编写了一个 gist 以证明:https://gist.github.com/3225564) - Jean Hominal