view Implab/ActionChainTaskBase.cs @ 151:ec91a6dfa5b3 v2

Added support for 'await' operator to promises
author cin
date Thu, 04 Feb 2016 02:43:05 +0300
parents eb793fbbe4ea
children 75103928da09
line wrap: on
line source

using System;
using System.Threading;

namespace Implab {
    public class ActionChainTaskBase : AbstractPromise {
        readonly Func<Exception, IPromise> m_error;
        readonly Func<Exception, IPromise> m_cancel;

        int m_cancelationLock;

        protected ActionChainTaskBase(Func<Exception, IPromise> error, Func<Exception, IPromise> cancel, bool autoCancellable) {
            m_error = error;
            m_cancel = cancel;
            if (autoCancellable)
                CancellationRequested(CancelOperation);
        }

        public void Reject(Exception error) {
            if (LockCancelation())
                HandleErrorInternal(error);
        }



        public override void CancelOperation(Exception reason) {
            if (LockCancelation()) {
                if (m_cancel != null) {
                    try {
                        m_cancel(reason).On(SetResult, SetError, SetCancelled);
                    } catch (Exception err) {
                        HandleErrorInternal(err);
                    }
                } else {
                    SetCancelled(reason);
                }
            }
        }

        protected void HandleErrorInternal(Exception error) {
            if (m_error != null) {
                try {
                    var p = m_error(error);
                    p.On(SetResult,SetError,SetCancelled);
                    CancellationRequested(p.Cancel);
                } catch (Exception err) {
                    SetError(err);
                }
            } else {
                SetError(error);
            }
        }

        protected bool LockCancelation() {
            return 0 == Interlocked.CompareExchange(ref m_cancelationLock, 1, 0);
        }
    }
}