A
A
Anton Ivanov2020-12-09 05:49:03
WPF
Anton Ivanov, 2020-12-09 05:49:03

Why is the View not updated when a property in the viewmodel is updated?

Inside the ViewModel, an asynchronous block is executed.
Before this block, the value of the ControlsEnabled property changes to false, inside this block it changes back to True.

More or less like this:

private void DoTheThing(string clientType)
{
    var applicationWorker = new ApplicationWorker();
    applicationWorker.StatusUpdated += (sender, s) =>
    {
            _syncContext.Post(o => StatusText = s, null); // обновление статуса в статусбаре
    };
    ControlsEnabled = false; // отключаем контролсы

    Task.Run(() =>
    {
             var result = applicationWorker.DoTheThing();
             
            _syncContext.Post(o => ControlsEnabled = true, null); // включаем контролсы (выполнение в потоке UI)
            ResetDataToDefaults();
    }).ContinueWith((t) =>
    {
        if (t.IsFaulted) SendFaultLog(t.Exception);
    }, TaskScheduler.FromCurrentSynchronizationContext()); ;
}


As you can understand, ControlsEnabled blocks the controls on the form so that the user does not stumble upon anything while the process is in progress. The problem is that the client very often , though not always, ControlsEnabled = truedoes not work. At the same time, it is clear that it ResetDataToDefaultsworks (the fields on the form are cleared, although they remain "disabled").

_syncContexti get in constructor like this: _syncContext = SynchronizationContext.Current
Before i started using _syncContext i used
Application.Current.Dispatcher.Invoke(delegate { ... })


In this case, sometimes the status change did not work for me (there are 10 of them changing while waiting for the end of work applicationWorker.DoTheThing). The first status was shown (and occasionally one from the middle) and that's it. When I changed to _syncContext, everything began to work like clockwork.

Now everything works correctly locally in 100% of cases, and the customer has a problem 4 times out of five.
I don't even know which way to dig.
If it's important, the class ApplicationWorkeris in a different assembly

PS I just noticed that it 's notResetDataToDefaults running on the UI thread. And yet, it works. So the problem is ? _syncContext.Post

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
soloveid, 2020-12-09
@soloveid

Perhaps it is not reproduced for you because you are testing in Debug mode,
and the user probably already has Release.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question