view Implab/FuncChainTaskBase.cs @ 187:dd4a3590f9c6 ref20160224

Reworked cancelation handling, if the cancel handler isn't specified the OperationCanceledException will be handled by the error handler Any unhandled OperationCanceledException will cause the promise cancelation
author cin
date Tue, 19 Apr 2016 17:35:20 +0300
parents eb793fbbe4ea
children 40d7fed4a09e
line wrap: on
line source

using System;

namespace Implab {
    public class FuncChainTaskBase<TResult> : AbstractTask<TResult> {
        readonly Func<Exception, IPromise<TResult>> m_error;
        readonly Func<Exception, IPromise<TResult>> m_cancel;

        protected FuncChainTaskBase( Func<Exception, IPromise<TResult>> error, Func<Exception, IPromise<TResult>> 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())
                HandleCancelInternal(reason);
        }

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

        protected void HandleCancelInternal(Exception reason) {
            if (m_cancel != null) {
                try {
                    var p = m_cancel(reason);
                    p.On(SetResult, HandleErrorInternal, SetCancelledInternal);
                    CancellationRequested(p.Cancel);
                } catch (Exception err) {
                    HandleErrorInternal(err);
                }
            } else {
                HandleErrorInternal(reason ?? new OperationCanceledException());
            }
        }
    }
}