144
|
1 using System;
|
|
2 using System.Threading;
|
|
3
|
|
4 namespace Implab {
|
|
5 public class FuncTaskBase<TResult> : AbstractPromise<TResult> {
|
|
6 readonly Func<Exception, TResult> m_cancel;
|
|
7 readonly Func<Exception, TResult> m_error;
|
|
8
|
|
9 int m_cancelationLock;
|
|
10
|
|
11 protected FuncTaskBase( Func<Exception, TResult> error, Func<Exception, TResult> cancel) {
|
|
12 m_error = error;
|
|
13 m_cancel = cancel;
|
|
14 }
|
|
15
|
|
16 public void Reject(Exception error) {
|
|
17 Safe.ArgumentNotNull(error, "error");
|
|
18 if (LockCancelation())
|
|
19 HandleErrorInternal(error);
|
|
20 }
|
|
21
|
|
22 protected void HandleErrorInternal(Exception error) {
|
|
23 if (m_error != null) {
|
|
24 try {
|
|
25 SetResult(m_error(error));
|
|
26 } catch(Exception err) {
|
|
27 SetError(err);
|
|
28 }
|
|
29 } else {
|
|
30 SetError(error);
|
|
31 }
|
|
32 }
|
|
33
|
|
34 public override void CancelOperation(Exception reason) {
|
|
35 if (LockCancelation()) {
|
|
36 if (m_cancel != null) {
|
|
37 try {
|
|
38 SetResult(m_cancel(reason));
|
|
39 } catch (Exception err) {
|
|
40 HandleErrorInternal(err);
|
|
41 }
|
|
42 } else {
|
|
43 SetCancelled(reason);
|
|
44 }
|
|
45 }
|
|
46 }
|
|
47
|
|
48 protected bool LockCancelation() {
|
|
49 return 0 == Interlocked.CompareExchange(ref m_cancelationLock, 1, 0);
|
|
50 }
|
|
51 }
|
|
52 }
|
|
53
|