在WPF中使用Unity解析时,SynchronizationContext.Current为null [英] SynchronizationContext.Current is null on resolving with Unity in WPF

查看:292
本文介绍了在WPF中使用Unity解析时,SynchronizationContext.Current为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个WPF代码,看起来像这样.

I have a WPF Code which looks something like this.

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值.

I use Unity to Resolve the above AlphaProductesVM. This is instant when the Module is discovered using PRISM and the UnityBootstrapper. At runtime .ObserveOn(SynchronizationContext.Current) throws an exception and SynchronizationContext.Current has a null value in it.

推荐答案

SynchronizationContext.Current 属性仅在主线程上调用时会返回一个值.

如果您需要在线程 SynchronizationContext 对象>除了主线程之外,您可以传递 SynchronizationContext 与主线程相关联的实例与需要它的类作为依赖项.

If you need to use a SynchronizationContext object in threads other than the main thread, you could pass the SynchronizationContext instance associated to the main thread to the classes that need it as a dependency.

如果选择此解决方案,则可以注册 SynchronizationContext 对象从 SynchronizationContext.Current 属性获得主线程作为容器中的 singleton .这样一来,所有对 SynchronizationContext 的请求都将自动得到满足通过带有单例的容器:

If you choose this solution, you could register the SynchronizationContext object obtained from the SynchronizationContext.Current property on the main thread as a singleton in your container. That way all requests for a SynchronizationContext from that point on will automatically be satisfied by the container with the singleton:

// Must run in the main thread
container.RegisterInstance(SynchronizationContext.Current);

这篇关于在WPF中使用Unity解析时,SynchronizationContext.Current为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆