1
\$\begingroup\$

In an app the UI is updated from different threads. To queue this, I have created a utility class

public class AsyncChainedActions
{
    private Task _lastTask;
    public AsyncChainedActions()
    {
        _lastTask = Task.Run(() => { });
    }

    public void AddToAsyncChain(Action action, [CallerMemberName] string 
     caller = null)
    {
        _lastTask = _lastTask.ContinueWith(o =>
        {
            try
            {
                action();
            }
            catch (Exception ex)
            {
                PublishError($"process {caller} message 
              from service", ex);
            }
            o.Dispose();
        });
    }
}

util class is used as below

public class UpdateManager
{

  public ObservableCollection<Person> Persons{get;set;}//bound to a data 
  //grid
  public UpdateManager()
 {
   Event1.Subscribe(Event1Update);
   Event2.Subscribe(Event2Update);

 }

 private void Event1Update(Person person)
 {
  _asyncChainedActions.AddToAsyncChain(() =>
  {
     if(NotValidUpdate(person)) return;


     _updateUi.ExecuteOnMainDispatcher(() => 
   {
     var update = Persons.FirstOrDefault(x => x.Id == person.Id );
     if(update!=null)
     {
       update.Name = person.Name;
        update.Age= person.Age;
       update.Address= person.Address;
    }
   });                
 });
}

}

The events sometimes happens many times a second. In certain times the values updated on the Person object is not reflected in the UI grid. I confirm the value is indeed updated in the object, but it is just that it is not reflected in the UI. It happens only sometimes. I think it is something to do with the dispatcher updates happening in the chain adn binding delays.

Do you see any issue with the async chain approach?

\$\endgroup\$
  • \$\begingroup\$ What's the benefit of this over a plain dispatch into the UI thread? As far as I can see you queue actions you will then always execute in the UI thread: you add overhead without visible benefits. \$\endgroup\$ – Adriano Repetti May 28 at 16:14
  • \$\begingroup\$ I just edited the code.There are some checks which need not be done in UI thread, so it is kept outside the dispatcher \$\endgroup\$ – Jimmy May 28 at 16:18
  • \$\begingroup\$ This is a question. If it is done in plain dispatcher thread, will the thread honor the order of the events? \$\endgroup\$ – Jimmy May 28 at 16:20
  • 1
    \$\begingroup\$ What happened to this part //.........other updates? Please post everything. \$\endgroup\$ – t3chb0t May 28 at 16:35
  • 1
    \$\begingroup\$ I'm voting to close this question because the code is still incomplete, e.g. we don't know what _updateUi is. There are also other variables/properties that are undefined. \$\endgroup\$ – t3chb0t May 28 at 17:17

Browse other questions tagged or ask your own question.