145
|
1 using System;
|
|
2 using System.Threading;
|
|
3
|
|
4 namespace Implab {
|
|
5 public class ActionChainTaskBase : AbstractPromise {
|
|
6 readonly Func<Exception, IPromise> m_error;
|
|
7 readonly Func<Exception, IPromise> m_cancel;
|
|
8
|
|
9 int m_cancelationLock;
|
|
10
|
149
|
11 protected ActionChainTaskBase(Func<Exception, IPromise> error, Func<Exception, IPromise> cancel, bool autoCancellable) {
|
145
|
12 m_error = error;
|
|
13 m_cancel = cancel;
|
149
|
14 if (autoCancellable)
|
|
15 CancellationRequested(CancelOperation);
|
145
|
16 }
|
|
17
|
|
18 public void Reject(Exception error) {
|
|
19 if (LockCancelation())
|
|
20 HandleErrorInternal(error);
|
|
21 }
|
|
22
|
|
23 public override void CancelOperation(Exception reason) {
|
149
|
24 if (LockCancelation()) {
|
186
|
25 if (!(reason is OperationCanceledException))
|
|
26 reason = reason != null ? new OperationCanceledException(null, reason) : new OperationCanceledException();
|
|
27
|
149
|
28 if (m_cancel != null) {
|
|
29 try {
|
186
|
30 m_cancel(reason).On(SetResult, HandleErrorInternal, HandleCancelInternal);
|
149
|
31 } catch (Exception err) {
|
|
32 HandleErrorInternal(err);
|
|
33 }
|
|
34 } else {
|
186
|
35 HandleErrorInternal(reason);
|
145
|
36 }
|
|
37 }
|
|
38 }
|
|
39
|
186
|
40 void HandleCancelInternal(Exception reason) {
|
|
41 if (!(reason is OperationCanceledException))
|
|
42 reason = reason != null ? new OperationCanceledException(null, reason) : new OperationCanceledException();
|
|
43 HandleErrorInternal(reason);
|
|
44 }
|
|
45
|
|
46 void HandleErrorInternal(Exception error) {
|
145
|
47 if (m_error != null) {
|
|
48 try {
|
149
|
49 var p = m_error(error);
|
186
|
50 p.On(SetResult, SetError, SetCancelled);
|
149
|
51 CancellationRequested(p.Cancel);
|
|
52 } catch (Exception err) {
|
186
|
53 error = err;
|
145
|
54 }
|
|
55 } else {
|
186
|
56 SetErrorInternal(error);
|
|
57 }
|
|
58 }
|
|
59
|
|
60 void SetErrorInternal(Exception error) {
|
|
61 while (error is PromiseTransientException)
|
|
62 error = error.InnerException;
|
|
63
|
|
64 if (error is OperationCanceledException)
|
|
65 SetCancelled(error);
|
|
66 else
|
145
|
67 SetError(error);
|
|
68 }
|
|
69
|
|
70 protected bool LockCancelation() {
|
|
71 return 0 == Interlocked.CompareExchange(ref m_cancelationLock, 1, 0);
|
|
72 }
|
|
73 }
|
|
74 }
|
|
75
|