0

We have some models that get data using tasks and I've been doing some testing and noticed that it seems like UI (STA Thread) elements can be modified by background tasks. This was not previously the case. Has something changed with VS 2017 or .net 4.7?

public class FancyModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private string _state;

    public FancyModel(ILongRunningOperation opGetter)
    {
        Task.Run(() =>
          {
             State = opGetter.LongRunningOperation();
          });
    }

    public string State 
    { 
      get { return _state; }
      set {
            _state = value;
            PropertyChanged?.Invoke(this, nameof(State)); 
          }
    }
}
fanuc_bob
  • 857
  • 1
  • 7
  • 20
  • Just because it doesn't throw an exception doesn't mean that it's working, it just means that you don't realize that you're performing an unsafe operation. – Servy Jul 14 '17 at 17:17
  • https://stackoverflow.com/questions/1321423/does-wpf-databinding-marshall-changes-to-the-ui-thread – Kevin Gosse Jul 14 '17 at 17:18
  • INPC events are automatically marshalled as of... er, NET something point something. OCs are still thread centric. DPs are also. –  Jul 14 '17 at 18:21
  • Thanks @KevinGosse, that helped me understand – fanuc_bob Jul 14 '17 at 20:10

1 Answers1

0

This code is actually not waiting for the method to return. The long operation will to run on a separate background pool thread and when it returns will update the Status value. Its fire and forget the scenario. The dispatcher is generally used when there are chances that the objects we want to use belongs to another thread from the current thread. The principle of thread affinity when violates we use dispatcher. The last is in case of suspicious code of threading Create different manual threads and try calling the code pieces in order to simulate scenarios. For example in the current scenario create view model from different thread other than the main thread and try executing. One can watch for thread specific exceptions. There are no changes in newer. Net version as you think. Refer this for more info https://blogs.msdn.microsoft.com/dotnet/2017/04/05/announcing-the-net-framework-4-7/

Ramankingdom
  • 1,478
  • 2
  • 12
  • 17