Please explain RelayCommand implementation

Mar 23, 2015 at 1:51 PM
Edited Mar 23, 2015 at 2:40 PM
Hi,

I am reading the implementation of RelayCommand and trying to understand it a little better.
    public event EventHandler CanExecuteChanged
    {
        add
        {
            if (_canExecute != null)
            {
                // add event handler to local handler backing field in a thread safe manner
                EventHandler handler2;
                EventHandler canExecuteChanged = _requerySuggestedLocal;

                do
                {
                    handler2 = canExecuteChanged;
                    EventHandler handler3 = (EventHandler)Delegate.Combine(handler2, value);
                    canExecuteChanged = System.Threading.Interlocked.CompareExchange<EventHandler>(
                        ref _requerySuggestedLocal, 
                        handler3, 
                        handler2);
                } 
                while (canExecuteChanged != handler2); __

                CommandManager.RequerySuggested += value;
            }
        }

        remove
        {
            if (_canExecute != null)
            {
                // removes an event handler from local backing field in a thread safe manner
                EventHandler handler2;
                EventHandler canExecuteChanged = this._requerySuggestedLocal;

                do
                {
                    handler2 = canExecuteChanged;
                    EventHandler handler3 = (EventHandler)Delegate.Remove(handler2, value);
                    canExecuteChanged = System.Threading.Interlocked.CompareExchange<EventHandler>(
                        ref this._requerySuggestedLocal, 
                        handler3, 
                        handler2);
                } 
                while (canExecuteChanged != handler2); 

                CommandManager.RequerySuggested -= value;
            }
        }
    }
Could you please explain why is the while loop required in the event add and remove blocks and why is it required to combine handlers?

Thanks,