view Implab/FuncTaskBase.cs @ 160:5802131432e4 v2

fixed regression: race condition in Promise DFA refactoring
author cin
date Thu, 18 Feb 2016 19:38:54 +0300
parents eb793fbbe4ea
children dd4a3590f9c6
line wrap: on
line source

using System;
using System.Threading;

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

        int m_cancelationLock;

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

        public void Reject(Exception error) {
            Safe.ArgumentNotNull(error, "error");
            if (LockCancelation())
                HandleErrorInternal(error);
        }

        protected void HandleErrorInternal(Exception error) {
            if (m_error != null) {
                try {
                    SetResult(m_error(error));
                } catch(Exception err) {
                    SetError(err);
                }
            } else {
                SetError(error);
            }
        }

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

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