comparison Implab/FuncTaskBase.cs @ 187:dd4a3590f9c6 ref20160224

Reworked cancelation handling, if the cancel handler isn't specified the OperationCanceledException will be handled by the error handler Any unhandled OperationCanceledException will cause the promise cancelation
author cin
date Tue, 19 Apr 2016 17:35:20 +0300
parents eb793fbbe4ea
children 40d7fed4a09e
comparison
equal deleted inserted replaced
186:75103928da09 187:dd4a3590f9c6
1 using System; 1 using System;
2 using System.Threading;
3 2
4 namespace Implab { 3 namespace Implab {
5 public class FuncTaskBase<TResult> : AbstractPromise<TResult> { 4 public class FuncTaskBase<TResult> : AbstractTask<TResult> {
6 readonly Func<Exception, TResult> m_cancel; 5 readonly Func<Exception, TResult> m_cancel;
7 readonly Func<Exception, TResult> m_error; 6 readonly Func<Exception, TResult> m_error;
8
9 int m_cancelationLock;
10 7
11 protected FuncTaskBase( Func<Exception, TResult> error, Func<Exception, TResult> cancel, bool autoCancellable) { 8 protected FuncTaskBase( Func<Exception, TResult> error, Func<Exception, TResult> cancel, bool autoCancellable) {
12 m_error = error; 9 m_error = error;
13 m_cancel = cancel; 10 m_cancel = cancel;
14 if (autoCancellable) 11 if (autoCancellable)
24 protected void HandleErrorInternal(Exception error) { 21 protected void HandleErrorInternal(Exception error) {
25 if (m_error != null) { 22 if (m_error != null) {
26 try { 23 try {
27 SetResult(m_error(error)); 24 SetResult(m_error(error));
28 } catch(Exception err) { 25 } catch(Exception err) {
29 SetError(err); 26 SetErrorInternal(err);
30 } 27 }
31 } else { 28 } else {
32 SetError(error); 29 SetErrorInternal(error);
33 } 30 }
34 } 31 }
35 32
36 public override void CancelOperation(Exception reason) { 33 public override void CancelOperation(Exception reason) {
37 if (LockCancelation()) { 34 if (LockCancelation())
38 if (m_cancel != null) { 35 HandleCancelInternal(reason);
39 try { 36 }
40 SetResult(m_cancel(reason)); 37
41 } catch (Exception err) { 38 protected void HandleCancelInternal(Exception reason) {
42 HandleErrorInternal(err); 39 if (m_cancel != null) {
43 } 40 try {
44 } else { 41 SetResult(m_cancel(reason));
45 SetCancelled(reason); 42 } catch (Exception err) {
43 HandleErrorInternal(err);
46 } 44 }
45 } else {
46 HandleErrorInternal(reason ?? new OperationCanceledException());
47 } 47 }
48 } 48 }
49 49
50 protected bool LockCancelation() {
51 return 0 == Interlocked.CompareExchange(ref m_cancelationLock, 1, 0);
52 }
53 } 50 }
54 } 51 }
55 52