145
|
1 using System;
|
|
2 using System.Threading;
|
|
3
|
|
4 namespace Implab {
|
|
5 public class FuncChainTaskBase<TResult> : AbstractPromise<TResult> {
|
|
6 readonly Func<Exception, IPromise<TResult>> m_error;
|
|
7 readonly Func<Exception, IPromise<TResult>> m_cancel;
|
|
8
|
|
9 int m_cancelationLock;
|
|
10
|
149
|
11 protected FuncChainTaskBase( Func<Exception, IPromise<TResult>> error, Func<Exception, IPromise<TResult>> 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()) {
|
|
25 if (m_cancel != null) {
|
|
26 try {
|
|
27 m_cancel(reason).On(SetResult, HandleErrorInternal, SetCancelled);
|
|
28 } catch (Exception err) {
|
|
29 HandleErrorInternal(err);
|
|
30 }
|
|
31 } else {
|
|
32 SetCancelled(reason);
|
145
|
33 }
|
|
34 }
|
|
35
|
|
36 }
|
|
37
|
|
38 protected void HandleErrorInternal(Exception error) {
|
|
39 if (m_error != null) {
|
|
40 try {
|
149
|
41 var operation = m_error(error);
|
|
42
|
|
43 operation.On(SetResult, SetError, SetCancelled);
|
|
44 CancellationRequested(operation.Cancel);
|
145
|
45 } catch(Exception err) {
|
|
46 SetError(err);
|
|
47 }
|
|
48 } else {
|
|
49 SetError(error);
|
|
50 }
|
|
51 }
|
|
52
|
|
53 protected bool LockCancelation() {
|
|
54 return 0 == Interlocked.CompareExchange(ref m_cancelationLock, 1, 0);
|
|
55 }
|
|
56 }
|
|
57 }
|
|
58
|