我有一个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值。
发布于 2012-02-21 20:35:29
当在主线程上调用时,SynchronizationContext.Current属性将只返回值。
如果需要在主线程以外的线程中使用SynchronizationContext对象,可以将与主线程关联的SynchronizationContext实例作为依赖项传递给需要它的类。
如果选择此解决方案,则可以将从主线程上的SynchronizationContext.Current属性获取的SynchronizationContext对象注册为容器中的单例对象。这样,从那时起对SynchronizationContext的所有请求都将由容器使用单例自动满足:
// Must run in the main thread
container.RegisterInstance(SynchronizationContext.Current);发布于 2012-02-21 20:22:38
尽管有用于WPF的SynchronizationContext实现,但不建议使用它。WPF有指向build responsive applications的Dispatcher。
此外,只有在UI线程上时,SynchronizationContext.Current才会有一个值。如果您的逻辑在后台线程中运行,则Current将始终为空。
发布于 2012-02-21 21:32:10
我不确定这是否会是一个流行的建议,但你可以懒惰地创建和订阅你的收藏。然后,从UI线程对NwCustomers的第一次访问将正确启动所有操作。
public AlphaProductesVM (){}
public ObservableCollection<Alphabetical_list_of_product> NwCustomers
{
get {
if(_NwCustomers == null)
{
_NwCustomers = new ObservableCollection<Alphabetical_list_of_product>();
var repository = new NorthwindRepository();
repository
.GetAllProducts()
.ObserveOn(SynchronizationContext.Current)
.Subscribe(AddElement);
}
return _NwCustomers;
}
}或者,如果您将UI线程的dispatcher注入到视图模型中,您可以在构造函数中订阅它。
var repository = new NorthwindRepository();
repository
.GetAllProducts()
.ObserveOn(theUIdispatcher)
.Subscribe(AddElement);https://stackoverflow.com/questions/9377290
复制相似问题