ASync AddNewCore()

ASync AddNewCore()

Old forum URL: forums.lhotka.net/forums/t/7305.aspx


rfcdejong posted on Monday, July 20, 2009

I had to answer an question from a collegue on how to implement AddNewCore() with ASync. Well i didn't know for sure on how to implement it, so my answer was far from good.

With Sync it goes like:

 

protected override object AddNewCore()
{
  var item = DataPortal.Create<C>();
  Add(item);
  return item;
}

How should this be done ASync ?

RockfordLhotka replied on Monday, July 20, 2009

On .NET the method isn't designed for async, so I don't think you can do it. Data binding (mostly datagrid controls) will be expecting the new value as a result from the method, and will almost certainly fail to work properly if you don't return the value.

On SL the method is designed for async (because we created it as part of CSLA), so the method returns void and there's an easy way to handle the callback scenario.

rfcdejong replied on Monday, July 20, 2009

Thanks!

PS: im missing a button "mark as answer" on this community server forum ;)

Calin replied on Monday, March 01, 2010

Hi there,

I found a solution to this problem, not the most elegant one, but it does what you requiere:

 

[NonSerialized]

        private FrameworkElement _frameWorkElement;

 

        private delegate Week Creator(int facilityId);

 

        protected override object AddNewCore()

        {

            _frameWorkElement = new FrameworkElement();

            Creator creator = facilityId =>

                                  {

                                      if (facilityId != 0)

                                      {

                                          return Week.Create(new SingleCriteria<Week, int>(facilityId));

                                      }

                                      return Week.Create();

                                  };

            if (Parent is Menu)

            {

                creator.BeginInvoke((Parent as Menu).FacilityId, CreatorCallback, creator);

            }

            else

            {

                creator.BeginInvoke(0, CreatorCallback, creator);

            }

 

            return null;

        }

 

        private void CreatorCallback(IAsyncResult result)

        {

            if (_frameWorkElement.Dispatcher.Thread != Thread.CurrentThread)

            {

                _frameWorkElement.Dispatcher.Invoke(

                    (Action)delegate

                    {

                        Creator creator = (Creator)result.AsyncState;

                        Week week = creator.EndInvoke(result);

                        Add(week);

                    });

            }

        }

 

What I basiclly do is intially return null, and add the real item after it has been created.

Let me know if it helps or you have any improvements.

 

Regards,

Copyright (c) Marimer LLC