SynchronizationContext.Current is null on resolving with Unity in WPF

后端 未结 3 541
耶瑟儿~
耶瑟儿~ 2021-01-06 00:50

I have a WPF Code which looks something like this.

public class AlphaProductesVM : BaseModel
{
    private  ObservableCollection

        
相关标签:
3条回答
  • 2021-01-06 01:19

    I'm not sure if this will be a popular suggestion, but you could lazily create and subscribe to your collection. Then the first access to NwCustomers from the UI thread will kick everything off correctly.

    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; 
        }
    }
    

    or, if you inject the UI thread's dispatcher into your view model you can subscribe on that in the constructor.

                  var repository = new NorthwindRepository();
                      repository
                      .GetAllProducts()
                      .ObserveOn(theUIdispatcher)
                      .Subscribe(AddElement);
    
    0 讨论(0)
  • 2021-01-06 01:30

    The SynchronizationContext.Current property will only return a value when invoked on the main thread.

    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.

    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);
    
    0 讨论(0)
  • 2021-01-06 01:36

    Although there is an implementation of SynchronizationContextfor WPF it is not recommended for use. WPF has the Dispatcher to build responsive applications.

    In addition SynchronizationContext.Current only has a value if you are on the UI thread. If your logic runs in a background thread Current will always be null.

    0 讨论(0)
提交回复
热议问题