using System; namespace Implab { public class FuncTaskBase : AbstractTask { readonly Func m_cancel; readonly Func m_error; protected FuncTaskBase( Func error, Func 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) { SetErrorInternal(err); } } else { SetErrorInternal(error); } } public override void CancelOperation(Exception reason) { if (LockCancelation()) HandleCancelInternal(reason); } protected void HandleCancelInternal(Exception reason) { if (m_cancel != null) { try { SetResult(m_cancel(reason)); } catch (Exception err) { HandleErrorInternal(err); } } else { HandleErrorInternal(reason ?? new OperationCanceledException()); } } } }