diff Implab/ActionTaskBase.cs @ 145:706fccb85524 v2

RC: cancellation support for promises + tests
author cin
date Sun, 08 Mar 2015 02:52:27 +0300
parents
children eb793fbbe4ea
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Implab/ActionTaskBase.cs	Sun Mar 08 02:52:27 2015 +0300
@@ -0,0 +1,55 @@
+using System;
+using System.Threading;
+
+namespace Implab {
+    public class ActionTaskBase : AbstractPromise {
+        readonly Action<Exception> m_cancel;
+        readonly Action<Exception> m_error;
+
+        int m_cancelationLock;
+
+        protected ActionTaskBase( Action<Exception> error, Action<Exception> cancel) {
+            m_error = error;
+            m_cancel = cancel;
+        }
+
+        public void Reject(Exception error) {
+            Safe.ArgumentNotNull(error, "error");
+            if (LockCancelation())
+                HandleErrorInternal(error);
+        }
+
+        protected void HandleErrorInternal(Exception error) {
+            if (m_error != null) {
+                try {
+                    m_error(error);
+                    SetResult();
+                } catch(Exception err) {
+                    SetError(err);
+                }
+            } else {
+                SetError(error);
+            }
+        }
+
+        public override void CancelOperation(Exception reason) {
+            if (LockCancelation()) {
+                if (m_cancel != null) {
+                    try {
+                        m_cancel(reason);
+                        SetResult();
+                    } catch (Exception err) {
+                        HandleErrorInternal(err);
+                    }
+                } else {
+                    SetCancelled(reason);
+                }
+            }
+        }
+
+        protected bool LockCancelation() {
+            return 0 == Interlocked.CompareExchange(ref m_cancelationLock, 1, 0);
+        }
+    }
+}
+