annotate Implab/Promise.cs @ 107:f5220e5472ef v2

minor fixes and optimizations
author cin
date Tue, 11 Nov 2014 04:14:21 +0300
parents d4e38929ce36
children 38d6a4db35d7
Ignore whitespace changes - Everywhere: Within whitespace: At end of lines:
rev   line source
2
aa367305156b small fixes
cin
parents: 1
diff changeset
1 using System;
aa367305156b small fixes
cin
parents: 1
diff changeset
2 using System.Collections.Generic;
aa367305156b small fixes
cin
parents: 1
diff changeset
3 using System.Reflection;
aa367305156b small fixes
cin
parents: 1
diff changeset
4 using System.Threading;
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
5 using Implab.Parallels;
2
aa367305156b small fixes
cin
parents: 1
diff changeset
6
aa367305156b small fixes
cin
parents: 1
diff changeset
7 namespace Implab {
aa367305156b small fixes
cin
parents: 1
diff changeset
8
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
9 /// <summary>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
10 /// Класс для асинхронного получения результатов. Так называемое "обещание".
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
11 /// </summary>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
12 /// <typeparam name="T">Тип получаемого результата</typeparam>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
13 /// <remarks>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
14 /// <para>Сервис при обращении к его методу дает обещаиние о выполнении операции,
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
15 /// клиент получив такое обещание может установить ряд обратных вызово для получения
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
16 /// событий выполнения обещания, тоесть завершения операции и предоставлении результатов.</para>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
17 /// <para>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
18 /// Обещение может быть как выполнено, так и выполнено с ошибкой. Для подписки на
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
19 /// данные события клиент должен использовать методы <c>Then</c>.
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
20 /// </para>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
21 /// <para>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
22 /// Сервис, в свою очередь, по окончанию выполнения операции (возможно с ошибкой),
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
23 /// использует методы <c>Resolve</c> либо <c>Reject</c> для оповещения клиетна о
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
24 /// выполнении обещания.
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
25 /// </para>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
26 /// <para>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
27 /// Если сервер успел выполнить обещание еще до того, как клиент на него подписался,
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
28 /// то в момент подписки клиента будут вызваны соответсвующие события в синхронном
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
29 /// режиме и клиент будет оповещен в любом случае. Иначе, обработчики добавляются в
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
30 /// список в порядке подписания и в этом же порядке они будут вызваны при выполнении
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
31 /// обещания.
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
32 /// </para>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
33 /// <para>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
34 /// Обрабатывая результаты обещания можно преобразовывать результаты либо инициировать
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
35 /// связанные асинхронные операции, которые также возвращают обещания. Для этого следует
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
36 /// использовать соответствующую форму методе <c>Then</c>.
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
37 /// </para>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
38 /// <para>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
39 /// Также хорошим правилом является то, что <c>Resolve</c> и <c>Reject</c> должен вызывать
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
40 /// только инициатор обещания иначе могут возникнуть противоречия.
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
41 /// </para>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
42 /// </remarks>
25
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
43 public class Promise<T> : IPromise<T> {
2
aa367305156b small fixes
cin
parents: 1
diff changeset
44
106
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
45 protected abstract class AbstractHandler : MTCustomQueueNode<AbstractHandler> {
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
46 public abstract void Resolve(T result);
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
47 public abstract void Reject(Exception error);
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
48 public abstract void Cancel();
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
49 }
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
50
107
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
51 protected class RemapDescriptor<T2> : AbstractHandler {
106
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
52
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
53 readonly Func<T,T2> m_resultHandler;
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
54 readonly Func<Exception,T2> m_errorHandler;
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
55 readonly Action m_cancellHandler;
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
56 readonly Promise<T2> m_medium;
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
57
107
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
58 public RemapDescriptor(Func<T,T2> resultHandler, Func<Exception,T2> errorHandler, Action cancelHandler, Promise<T2> medium) {
106
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
59 m_resultHandler = resultHandler;
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
60 m_errorHandler = errorHandler;
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
61 m_cancellHandler = cancelHandler;
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
62 m_medium = medium;
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
63 }
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
64
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
65 public override void Resolve(T result) {
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
66 if (m_resultHandler != null) {
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
67 try {
106
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
68 if (m_medium != null)
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
69 m_medium.Resolve(m_resultHandler(result));
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
70 else
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
71 m_resultHandler(result);
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
72 } catch (Exception e) {
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
73 Reject(e);
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
74 }
106
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
75 } else if(m_medium != null)
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
76 m_medium.Resolve(default(T2));
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
77 }
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
78
106
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
79 public override void Reject(Exception error) {
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
80 if (m_errorHandler != null) {
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
81 try {
106
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
82 var res = m_errorHandler(error);
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
83 if (m_medium != null)
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
84 m_medium.Resolve(res);
107
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
85 } catch (Exception err2) {
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
86 if (m_medium != null)
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
87 m_medium.Reject(err2);
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
88 }
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
89 } else if (m_medium != null)
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
90 m_medium.Reject(error);
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
91 }
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
92
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
93 public override void Cancel() {
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
94 if (m_cancellHandler != null) {
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
95 try {
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
96 m_cancellHandler();
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
97 } catch (Exception err) {
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
98 Reject(err);
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
99 return;
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
100 }
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
101 }
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
102 if (m_medium != null)
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
103 m_medium.Cancel();
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
104 }
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
105 }
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
106
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
107 protected class HandlerDescriptor : AbstractHandler {
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
108
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
109 readonly Action<T> m_resultHandler;
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
110 readonly Action<Exception> m_errorHandler;
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
111 readonly Action m_cancellHandler;
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
112 readonly Promise<T> m_medium;
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
113
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
114 public HandlerDescriptor(Action<T> resultHandler, Action<Exception> errorHandler, Action cancelHandler, Promise<T> medium) {
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
115 m_resultHandler = resultHandler;
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
116 m_errorHandler = errorHandler;
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
117 m_cancellHandler = cancelHandler;
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
118 m_medium = medium;
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
119 }
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
120
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
121 public override void Resolve(T result) {
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
122 if (m_resultHandler != null) {
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
123 try {
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
124 m_resultHandler(result);
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
125 } catch (Exception e) {
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
126 Reject(e);
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
127 return;
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
128 }
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
129 }
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
130 if(m_medium != null)
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
131 m_medium.Resolve(result);
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
132 }
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
133
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
134 public override void Reject(Exception error) {
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
135 if (m_errorHandler != null) {
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
136 try {
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
137 m_errorHandler(error);
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
138 if (m_medium != null)
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
139 m_medium.Resolve(default(T));
72
d67b95eddaf4 promises refactoring
cin
parents: 71
diff changeset
140 } catch (Exception err2) {
106
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
141 if (m_medium != null)
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
142 m_medium.Reject(err2);
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
143 }
106
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
144 } else if (m_medium != null)
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
145 m_medium.Reject(error);
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
146 }
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
147
106
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
148 public override void Cancel() {
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
149 if (m_cancellHandler != null) {
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
150 try {
106
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
151 m_cancellHandler();
72
d67b95eddaf4 promises refactoring
cin
parents: 71
diff changeset
152 } catch (Exception err) {
d67b95eddaf4 promises refactoring
cin
parents: 71
diff changeset
153 Reject(err);
d67b95eddaf4 promises refactoring
cin
parents: 71
diff changeset
154 return;
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
155 }
72
d67b95eddaf4 promises refactoring
cin
parents: 71
diff changeset
156 }
106
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
157 if (m_medium != null)
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
158 m_medium.Cancel();
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
159 }
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
160 }
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
161
71
1714fd8678ef code cleanup
cin
parents: 66
diff changeset
162 const int UNRESOLVED_SATE = 0;
1714fd8678ef code cleanup
cin
parents: 66
diff changeset
163 const int TRANSITIONAL_STATE = 1;
1714fd8678ef code cleanup
cin
parents: 66
diff changeset
164 const int SUCCEEDED_STATE = 2;
1714fd8678ef code cleanup
cin
parents: 66
diff changeset
165 const int REJECTED_STATE = 3;
1714fd8678ef code cleanup
cin
parents: 66
diff changeset
166 const int CANCELLED_STATE = 4;
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
167
101
279e226dffdd code cleanup
cin
parents: 99
diff changeset
168 int m_childrenCount;
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
169 int m_state;
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
170 T m_result;
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
171 Exception m_error;
9
cin
parents: 7
diff changeset
172
106
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
173 readonly MTCustomQueue<AbstractHandler> m_handlers = new MTCustomQueue<AbstractHandler>();
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
174 //readonly MTQueue<AbstractHandler> m_handlers = new MTQueue<AbstractHandler>();
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
175
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
176 public Promise() {
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
177 }
2
aa367305156b small fixes
cin
parents: 1
diff changeset
178
101
279e226dffdd code cleanup
cin
parents: 99
diff changeset
179 public Promise(IPromise parent) {
33
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
180 if (parent != null)
107
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
181 AddMappers<T>(
76
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
182 null,
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
183 null,
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
184 () => {
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
185 if (parent.IsExclusive)
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
186 parent.Cancel();
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
187 },
104
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
188 null,
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
189 false
76
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
190 );
10
aa33d0bb8c0c implemeted new cancellable promises concept
cin
parents: 9
diff changeset
191 }
2
aa367305156b small fixes
cin
parents: 1
diff changeset
192
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
193 bool BeginTransit() {
71
1714fd8678ef code cleanup
cin
parents: 66
diff changeset
194 return UNRESOLVED_SATE == Interlocked.CompareExchange(ref m_state, TRANSITIONAL_STATE, UNRESOLVED_SATE);
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
195 }
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
196
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
197 void CompleteTransit(int state) {
71
1714fd8678ef code cleanup
cin
parents: 66
diff changeset
198 if (TRANSITIONAL_STATE != Interlocked.CompareExchange(ref m_state, state, TRANSITIONAL_STATE))
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
199 throw new InvalidOperationException("Can't complete transition when the object isn't in the transitional state");
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
200 }
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
201
25
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
202 void WaitTransition() {
71
1714fd8678ef code cleanup
cin
parents: 66
diff changeset
203 while (m_state == TRANSITIONAL_STATE) {
80
4f20870d0816 added memory barriers
cin
parents: 76
diff changeset
204 Thread.MemoryBarrier();
25
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
205 }
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
206 }
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
207
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
208 public bool IsResolved {
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
209 get {
80
4f20870d0816 added memory barriers
cin
parents: 76
diff changeset
210 Thread.MemoryBarrier();
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
211 return m_state > 1;
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
212 }
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
213 }
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
214
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
215 public bool IsCancelled {
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
216 get {
80
4f20870d0816 added memory barriers
cin
parents: 76
diff changeset
217 Thread.MemoryBarrier();
71
1714fd8678ef code cleanup
cin
parents: 66
diff changeset
218 return m_state == CANCELLED_STATE;
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
219 }
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
220 }
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
221
29
768f7deeb55b Added a casting method for promises.
cin
parents: 28
diff changeset
222 public Type PromiseType {
768f7deeb55b Added a casting method for promises.
cin
parents: 28
diff changeset
223 get { return typeof(T); }
768f7deeb55b Added a casting method for promises.
cin
parents: 28
diff changeset
224 }
768f7deeb55b Added a casting method for promises.
cin
parents: 28
diff changeset
225
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
226 /// <summary>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
227 /// Выполняет обещание, сообщая об успешном выполнении.
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
228 /// </summary>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
229 /// <param name="result">Результат выполнения.</param>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
230 /// <exception cref="InvalidOperationException">Данное обещание уже выполнено</exception>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
231 public void Resolve(T result) {
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
232 if (BeginTransit()) {
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
233 m_result = result;
71
1714fd8678ef code cleanup
cin
parents: 66
diff changeset
234 CompleteTransit(SUCCEEDED_STATE);
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
235 OnStateChanged();
25
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
236 } else {
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
237 WaitTransition();
71
1714fd8678ef code cleanup
cin
parents: 66
diff changeset
238 if (m_state != CANCELLED_STATE)
25
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
239 throw new InvalidOperationException("The promise is already resolved");
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
240 }
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
241 }
2
aa367305156b small fixes
cin
parents: 1
diff changeset
242
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
243 /// <summary>
33
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
244 /// Выполняет обещание, сообщая об успешном выполнении. Результатом выполнения будет пустое значения.
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
245 /// </summary>
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
246 /// <remarks>
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
247 /// Данный вариант удобен в случаях, когда интересен факт выполнения операции, нежели полученное значение.
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
248 /// </remarks>
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
249 public void Resolve() {
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
250 Resolve(default(T));
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
251 }
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
252
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
253 /// <summary>
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
254 /// Выполняет обещание, сообщая об ошибке
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
255 /// </summary>
16
cin
parents: 15
diff changeset
256 /// <remarks>
cin
parents: 15
diff changeset
257 /// Поскольку обещание должно работать в многопточной среде, при его выполнении сразу несколько потоков
cin
parents: 15
diff changeset
258 /// могу вернуть ошибку, при этом только первая будет использована в качестве результата, остальные
cin
parents: 15
diff changeset
259 /// будут проигнорированы.
cin
parents: 15
diff changeset
260 /// </remarks>
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
261 /// <param name="error">Исключение возникшее при выполнении операции</param>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
262 /// <exception cref="InvalidOperationException">Данное обещание уже выполнено</exception>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
263 public void Reject(Exception error) {
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
264 if (BeginTransit()) {
99
8ddf1648eca4 fixed TransientPromiseException handling
cin
parents: 96
diff changeset
265 m_error = error is TransientPromiseException ? error.InnerException : error;
71
1714fd8678ef code cleanup
cin
parents: 66
diff changeset
266 CompleteTransit(REJECTED_STATE);
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
267 OnStateChanged();
25
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
268 } else {
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
269 WaitTransition();
71
1714fd8678ef code cleanup
cin
parents: 66
diff changeset
270 if (m_state == SUCCEEDED_STATE)
25
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
271 throw new InvalidOperationException("The promise is already resolved");
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
272 }
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
273 }
2
aa367305156b small fixes
cin
parents: 1
diff changeset
274
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
275 /// <summary>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
276 /// Отменяет операцию, если это возможно.
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
277 /// </summary>
76
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
278 /// <remarks>Для определения была ли операция отменена следует использовать свойство <see cref="IsCancelled"/>.</remarks>
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
279 public void Cancel() {
101
279e226dffdd code cleanup
cin
parents: 99
diff changeset
280 if (BeginTransit()) {
71
1714fd8678ef code cleanup
cin
parents: 66
diff changeset
281 CompleteTransit(CANCELLED_STATE);
33
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
282 OnStateChanged();
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
283 }
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
284 }
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
285
76
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
286 /// <summary>
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
287 /// Последний обработчик в цепочки обещаний.
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
288 /// </summary>
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
289 /// <param name="success"></param>
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
290 /// <param name="error"></param>
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
291 /// <param name="cancel"></param>
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
292 /// <remarks>
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
293 /// <para>
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
294 /// Данный метод не создает связанного с текущим обещания и предназначен для окончания
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
295 /// фсинхронной цепочки.
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
296 /// </para>
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
297 /// <para>
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
298 /// Если данный метод вызвать несколько раз, либо добавить другие обработчики, то цепочка
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
299 /// не будет одиночной <see cref="IsExclusive"/> и, как следствие, будет невозможна отмена
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
300 /// всей цепи обещаний снизу (с самого последнего обещания).
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
301 /// </para>
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
302 /// </remarks>
104
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
303 public void On(Action<T> success, Action<Exception> error, Action cancel) {
75
4439140706d0 major refactoring, added tasks support
cin
parents: 74
diff changeset
304 if (success == null && error == null && cancel == null)
4439140706d0 major refactoring, added tasks support
cin
parents: 74
diff changeset
305 return;
4439140706d0 major refactoring, added tasks support
cin
parents: 74
diff changeset
306
107
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
307 AddHandler(success, error, cancel, null, false);
104
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
308 }
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
309
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
310 public void On(Action<T> success, Action<Exception> error) {
107
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
311 AddHandler(success, error, null, null, false);
104
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
312 }
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
313
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
314 public void On(Action<T> success) {
107
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
315 AddHandler(success, null, null, null, false);
75
4439140706d0 major refactoring, added tasks support
cin
parents: 74
diff changeset
316 }
4439140706d0 major refactoring, added tasks support
cin
parents: 74
diff changeset
317
104
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
318 public void On(Action handler, PromiseEventType events) {
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
319 Safe.ArgumentNotNull(handler, "handler");
75
4439140706d0 major refactoring, added tasks support
cin
parents: 74
diff changeset
320
104
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
321
107
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
322 AddHandler(
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
323 events.HasFlag(PromiseEventType.Success) ? new Action<T>(x => handler()) : null,
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
324 events.HasFlag(PromiseEventType.Error) ? new Action<Exception>( x => handler()) : null,
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
325 events.HasFlag(PromiseEventType.Cancelled) ? handler : null,
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
326 null,
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
327 false
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
328 );
75
4439140706d0 major refactoring, added tasks support
cin
parents: 74
diff changeset
329 }
4439140706d0 major refactoring, added tasks support
cin
parents: 74
diff changeset
330
101
279e226dffdd code cleanup
cin
parents: 99
diff changeset
331 public IPromise Error(Action<Exception> error) {
72
d67b95eddaf4 promises refactoring
cin
parents: 71
diff changeset
332 if (error == null)
d67b95eddaf4 promises refactoring
cin
parents: 71
diff changeset
333 return this;
d67b95eddaf4 promises refactoring
cin
parents: 71
diff changeset
334
101
279e226dffdd code cleanup
cin
parents: 99
diff changeset
335 var medium = new Promise<T>(this);
72
d67b95eddaf4 promises refactoring
cin
parents: 71
diff changeset
336
107
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
337 AddMappers(
72
d67b95eddaf4 promises refactoring
cin
parents: 71
diff changeset
338 null,
d67b95eddaf4 promises refactoring
cin
parents: 71
diff changeset
339 e => {
d67b95eddaf4 promises refactoring
cin
parents: 71
diff changeset
340 error(e);
d67b95eddaf4 promises refactoring
cin
parents: 71
diff changeset
341 return default(T);
d67b95eddaf4 promises refactoring
cin
parents: 71
diff changeset
342 },
d67b95eddaf4 promises refactoring
cin
parents: 71
diff changeset
343 null,
104
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
344 medium,
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
345 true
72
d67b95eddaf4 promises refactoring
cin
parents: 71
diff changeset
346 );
d67b95eddaf4 promises refactoring
cin
parents: 71
diff changeset
347
d67b95eddaf4 promises refactoring
cin
parents: 71
diff changeset
348 return medium;
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
349 }
2
aa367305156b small fixes
cin
parents: 1
diff changeset
350
11
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
351 /// <summary>
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
352 /// Handles error and allows to keep the promise.
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
353 /// </summary>
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
354 /// <remarks>
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
355 /// If the specified handler throws an exception, this exception will be used to reject the promise.
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
356 /// </remarks>
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
357 /// <param name="handler">The error handler which returns the result of the promise.</param>
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
358 /// <returns>New promise.</returns>
101
279e226dffdd code cleanup
cin
parents: 99
diff changeset
359 public IPromise<T> Error(Func<Exception,T> handler) {
11
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
360 if (handler == null)
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
361 return this;
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
362
101
279e226dffdd code cleanup
cin
parents: 99
diff changeset
363 var medium = new Promise<T>(this);
11
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
364
107
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
365 AddMappers(null, handler, null, medium, true);
11
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
366
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
367 return medium;
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
368 }
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
369
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
370 /// <summary>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
371 /// Позволяет преобразовать результат выполения операции к новому типу.
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
372 /// </summary>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
373 /// <typeparam name="TNew">Новый тип результата.</typeparam>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
374 /// <param name="mapper">Преобразование результата к новому типу.</param>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
375 /// <param name="error">Обработчик ошибки. Данный обработчик получит
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
376 /// исключение возникшее при выполнении операции.</param>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
377 /// <returns>Новое обещание, которое будет выполнено при выполнении исходного обещания.</returns>
96
daffa72a1cec Added the chaining method to the non-generic IPromise
cin
parents: 80
diff changeset
378 /// <param name = "cancel"></param>
101
279e226dffdd code cleanup
cin
parents: 99
diff changeset
379 public IPromise<TNew> Then<TNew>(Func<T, TNew> mapper, Func<Exception,TNew> error, Action cancel) {
76
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
380 Safe.ArgumentNotNull(mapper, "mapper");
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
381
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
382 // создаем прицепленное обещание
101
279e226dffdd code cleanup
cin
parents: 99
diff changeset
383 var medium = new Promise<TNew>(this);
2
aa367305156b small fixes
cin
parents: 1
diff changeset
384
107
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
385 AddMappers(
106
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
386 mapper,
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
387 error,
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
388 cancel,
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
389 medium,
104
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
390 true
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
391 );
2
aa367305156b small fixes
cin
parents: 1
diff changeset
392
76
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
393 return medium;
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
394 }
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
395
101
279e226dffdd code cleanup
cin
parents: 99
diff changeset
396 public IPromise<TNew> Then<TNew>(Func<T, TNew> mapper, Func<Exception,TNew> error) {
76
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
397 return Then(mapper, error, null);
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
398 }
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
399
101
279e226dffdd code cleanup
cin
parents: 99
diff changeset
400 public IPromise<TNew> Then<TNew>(Func<T, TNew> mapper) {
76
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
401 return Then(mapper, null, null);
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
402 }
2
aa367305156b small fixes
cin
parents: 1
diff changeset
403
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
404 /// <summary>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
405 /// Сцепляет несколько аснхронных операций. Указанная асинхронная операция будет вызвана после
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
406 /// выполнения текущей, а результат текущей операции может быть использован для инициализации
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
407 /// новой операции.
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
408 /// </summary>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
409 /// <typeparam name="TNew">Тип результата указанной асинхронной операции.</typeparam>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
410 /// <param name="chained">Асинхронная операция, которая должна будет начаться после выполнения текущей.</param>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
411 /// <param name="error">Обработчик ошибки. Данный обработчик получит
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
412 /// исключение возникшее при выполнении текуещй операции.</param>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
413 /// <returns>Новое обещание, которое будет выполнено по окончанию указанной аснхронной операции.</returns>
96
daffa72a1cec Added the chaining method to the non-generic IPromise
cin
parents: 80
diff changeset
414 /// <param name = "cancel"></param>
101
279e226dffdd code cleanup
cin
parents: 99
diff changeset
415 public IPromise<TNew> Chain<TNew>(Func<T, IPromise<TNew>> chained, Func<Exception,IPromise<TNew>> error, Action cancel) {
76
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
416
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
417 Safe.ArgumentNotNull(chained, "chained");
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
418
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
419 // проблема в том, что на момент связывания еще не начата асинхронная операция, поэтому нужно
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
420 // создать посредника, к которому будут подвызяваться следующие обработчики.
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
421 // когда будет выполнена реальная асинхронная операция, она обратиться к посреднику, чтобы
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
422 // передать через него результаты работы.
101
279e226dffdd code cleanup
cin
parents: 99
diff changeset
423 var medium = new Promise<TNew>(this);
2
aa367305156b small fixes
cin
parents: 1
diff changeset
424
106
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
425 Func<T,T> resultHandler = delegate(T result) {
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
426 if (medium.IsCancelled)
106
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
427 return default(T);
10
aa33d0bb8c0c implemeted new cancellable promises concept
cin
parents: 9
diff changeset
428
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
429 var promise = chained(result);
10
aa33d0bb8c0c implemeted new cancellable promises concept
cin
parents: 9
diff changeset
430
104
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
431 promise.On(
72
d67b95eddaf4 promises refactoring
cin
parents: 71
diff changeset
432 medium.Resolve,
76
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
433 medium.Reject,
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
434 () => medium.Reject(new OperationCanceledException()) // внешняя отмена связанной операции рассматривается как ошибка
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
435 );
33
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
436
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
437 // notify chained operation that it's not needed anymore
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
438 // порядок вызова Then, Cancelled важен, поскольку от этого
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
439 // зависит IsExclusive
104
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
440 medium.On(
101
279e226dffdd code cleanup
cin
parents: 99
diff changeset
441 null,
279e226dffdd code cleanup
cin
parents: 99
diff changeset
442 null,
279e226dffdd code cleanup
cin
parents: 99
diff changeset
443 () => {
279e226dffdd code cleanup
cin
parents: 99
diff changeset
444 if (promise.IsExclusive)
279e226dffdd code cleanup
cin
parents: 99
diff changeset
445 promise.Cancel();
279e226dffdd code cleanup
cin
parents: 99
diff changeset
446 }
279e226dffdd code cleanup
cin
parents: 99
diff changeset
447 );
106
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
448
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
449 return default(T);
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
450 };
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
451
101
279e226dffdd code cleanup
cin
parents: 99
diff changeset
452 Func<Exception,T> errorHandler;
76
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
453
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
454 if (error != null)
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
455 errorHandler = delegate(Exception e) {
72
d67b95eddaf4 promises refactoring
cin
parents: 71
diff changeset
456 try {
76
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
457 var promise = error(e);
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
458
104
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
459 promise.On(
76
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
460 medium.Resolve,
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
461 medium.Reject,
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
462 () => medium.Reject(new OperationCanceledException()) // внешняя отмена связанной операции рассматривается как ошибка
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
463 );
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
464
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
465 // notify chained operation that it's not needed anymore
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
466 // порядок вызова Then, Cancelled важен, поскольку от этого
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
467 // зависит IsExclusive
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
468 medium.Cancelled(() => {
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
469 if (promise.IsExclusive)
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
470 promise.Cancel();
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
471 });
72
d67b95eddaf4 promises refactoring
cin
parents: 71
diff changeset
472 } catch (Exception e2) {
d67b95eddaf4 promises refactoring
cin
parents: 71
diff changeset
473 medium.Reject(e2);
d67b95eddaf4 promises refactoring
cin
parents: 71
diff changeset
474 }
76
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
475 return default(T);
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
476 };
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
477 else
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
478 errorHandler = err => {
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
479 medium.Reject(err);
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
480 return default(T);
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
481 };
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
482
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
483
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
484 Action cancelHandler;
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
485 if (cancel != null)
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
486 cancelHandler = () => {
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
487 if (cancel != null)
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
488 cancel();
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
489 medium.Cancel();
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
490 };
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
491 else
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
492 cancelHandler = medium.Cancel;
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
493
107
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
494 AddMappers(
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
495 resultHandler,
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
496 errorHandler,
76
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
497 cancelHandler,
104
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
498 null,
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
499 true
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
500 );
2
aa367305156b small fixes
cin
parents: 1
diff changeset
501
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
502 return medium;
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
503 }
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
504
101
279e226dffdd code cleanup
cin
parents: 99
diff changeset
505 public IPromise<TNew> Chain<TNew>(Func<T, IPromise<TNew>> chained, Func<Exception,IPromise<TNew>> error) {
76
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
506 return Chain(chained, error, null);
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
507 }
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
508
101
279e226dffdd code cleanup
cin
parents: 99
diff changeset
509 public IPromise<TNew> Chain<TNew>(Func<T, IPromise<TNew>> chained) {
76
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
510 return Chain(chained, null, null);
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
511 }
2
aa367305156b small fixes
cin
parents: 1
diff changeset
512
26
f0bf98e4d22c refactoring
cin
parents: 25
diff changeset
513 public IPromise<T> Cancelled(Action handler) {
101
279e226dffdd code cleanup
cin
parents: 99
diff changeset
514 var medium = new Promise<T>(this);
104
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
515 AddHandler(null, null, handler, medium, false);
74
c4140283575c minor fixes
cin
parents: 72
diff changeset
516 return medium;
10
aa33d0bb8c0c implemeted new cancellable promises concept
cin
parents: 9
diff changeset
517 }
aa33d0bb8c0c implemeted new cancellable promises concept
cin
parents: 9
diff changeset
518
25
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
519 /// <summary>
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
520 /// Adds the specified handler for all cases (success, error, cancel)
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
521 /// </summary>
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
522 /// <param name="handler">The handler that will be called anyway</param>
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
523 /// <returns>self</returns>
76
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
524 public IPromise<T> Anyway(Action handler) {
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
525 Safe.ArgumentNotNull(handler, "handler");
104
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
526
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
527 var medium = new Promise<T>(this);
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
528
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
529 AddHandler(
107
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
530 x => handler(),
72
d67b95eddaf4 promises refactoring
cin
parents: 71
diff changeset
531 e => {
d67b95eddaf4 promises refactoring
cin
parents: 71
diff changeset
532 handler();
d67b95eddaf4 promises refactoring
cin
parents: 71
diff changeset
533 throw new TransientPromiseException(e);
d67b95eddaf4 promises refactoring
cin
parents: 71
diff changeset
534 },
d67b95eddaf4 promises refactoring
cin
parents: 71
diff changeset
535 handler,
104
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
536 medium,
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
537 true
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
538 );
104
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
539
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
540 return medium;
10
aa33d0bb8c0c implemeted new cancellable promises concept
cin
parents: 9
diff changeset
541 }
aa33d0bb8c0c implemeted new cancellable promises concept
cin
parents: 9
diff changeset
542
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
543 /// <summary>
29
768f7deeb55b Added a casting method for promises.
cin
parents: 28
diff changeset
544 /// Преобразует результат обещания к нужному типу
768f7deeb55b Added a casting method for promises.
cin
parents: 28
diff changeset
545 /// </summary>
768f7deeb55b Added a casting method for promises.
cin
parents: 28
diff changeset
546 /// <typeparam name="T2"></typeparam>
768f7deeb55b Added a casting method for promises.
cin
parents: 28
diff changeset
547 /// <returns></returns>
768f7deeb55b Added a casting method for promises.
cin
parents: 28
diff changeset
548 public IPromise<T2> Cast<T2>() {
75
4439140706d0 major refactoring, added tasks support
cin
parents: 74
diff changeset
549 return Then(x => (T2)(object)x, null);
29
768f7deeb55b Added a casting method for promises.
cin
parents: 28
diff changeset
550 }
768f7deeb55b Added a casting method for promises.
cin
parents: 28
diff changeset
551
768f7deeb55b Added a casting method for promises.
cin
parents: 28
diff changeset
552 /// <summary>
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
553 /// Дожидается отложенного обещания и в случае успеха, возвращает
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
554 /// его, результат, в противном случае бросает исключение.
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
555 /// </summary>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
556 /// <remarks>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
557 /// <para>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
558 /// Если ожидание обещания было прервано по таймауту, это не значит,
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
559 /// что обещание было отменено или что-то в этом роде, это только
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
560 /// означает, что мы его не дождались, однако все зарегистрированные
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
561 /// обработчики, как были так остались и они будут вызваны, когда
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
562 /// обещание будет выполнено.
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
563 /// </para>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
564 /// <para>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
565 /// Такое поведение вполне оправдано поскольку таймаут может истечь
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
566 /// в тот момент, когда началась обработка цепочки обработчиков, и
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
567 /// к тому же текущее обещание может стоять в цепочке обещаний и его
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
568 /// отклонение может привести к непрогнозируемому результату.
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
569 /// </para>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
570 /// </remarks>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
571 /// <param name="timeout">Время ожидания</param>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
572 /// <returns>Результат выполнения обещания</returns>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
573 public T Join(int timeout) {
10
aa33d0bb8c0c implemeted new cancellable promises concept
cin
parents: 9
diff changeset
574 var evt = new ManualResetEvent(false);
76
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
575 Anyway(() => evt.Set());
2
aa367305156b small fixes
cin
parents: 1
diff changeset
576
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
577 if (!evt.WaitOne(timeout, true))
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
578 throw new TimeoutException();
2
aa367305156b small fixes
cin
parents: 1
diff changeset
579
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
580 switch (m_state) {
71
1714fd8678ef code cleanup
cin
parents: 66
diff changeset
581 case SUCCEEDED_STATE:
10
aa33d0bb8c0c implemeted new cancellable promises concept
cin
parents: 9
diff changeset
582 return m_result;
71
1714fd8678ef code cleanup
cin
parents: 66
diff changeset
583 case CANCELLED_STATE:
10
aa33d0bb8c0c implemeted new cancellable promises concept
cin
parents: 9
diff changeset
584 throw new OperationCanceledException();
71
1714fd8678ef code cleanup
cin
parents: 66
diff changeset
585 case REJECTED_STATE:
10
aa33d0bb8c0c implemeted new cancellable promises concept
cin
parents: 9
diff changeset
586 throw new TargetInvocationException(m_error);
aa33d0bb8c0c implemeted new cancellable promises concept
cin
parents: 9
diff changeset
587 default:
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
588 throw new ApplicationException(String.Format("Invalid promise state {0}", m_state));
10
aa33d0bb8c0c implemeted new cancellable promises concept
cin
parents: 9
diff changeset
589 }
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
590 }
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
591
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
592 public T Join() {
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
593 return Join(Timeout.Infinite);
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
594 }
2
aa367305156b small fixes
cin
parents: 1
diff changeset
595
107
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
596 void AddMappers<T2>(Func<T,T2> success, Func<Exception,T2> error, Action cancel, Promise<T2> medium, bool inc) {
104
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
597 if (inc)
33
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
598 Interlocked.Increment(ref m_childrenCount);
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
599
107
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
600 AbstractHandler handler = new RemapDescriptor<T2>(success, error, cancel, medium);
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
601
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
602 bool queued;
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
603
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
604 if (!IsResolved) {
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
605 m_handlers.Enqueue(handler);
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
606 queued = true;
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
607 } else {
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
608 // the promise is in resolved state, just invoke the handled with minimum overhead
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
609 queued = false;
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
610 InvokeHandler(handler);
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
611 }
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
612
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
613 if (queued && IsResolved && m_handlers.TryDequeue(out handler))
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
614 // if the promise have been resolved while we was adding handler to the queue
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
615 // we can't guarantee that someone is still processing it
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
616 // therefore we will fetch a handler from the queue and execute it
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
617 // note that fetched handler may be not the one that we have added
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
618 // even we can fetch no handlers at all :)
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
619 InvokeHandler(handler);
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
620 }
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
621
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
622 void AddHandler(Action<T> success, Action<Exception> error, Action cancel, Promise<T> medium, bool inc) {
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
623 if (inc)
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
624 Interlocked.Increment(ref m_childrenCount);
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
625
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
626 AbstractHandler handler = new HandlerDescriptor(success, error, cancel, medium);
2
aa367305156b small fixes
cin
parents: 1
diff changeset
627
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
628 bool queued;
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
629
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
630 if (!IsResolved) {
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
631 m_handlers.Enqueue(handler);
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
632 queued = true;
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
633 } else {
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
634 // the promise is in resolved state, just invoke the handled with minimum overhead
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
635 queued = false;
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
636 InvokeHandler(handler);
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
637 }
2
aa367305156b small fixes
cin
parents: 1
diff changeset
638
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
639 if (queued && IsResolved && m_handlers.TryDequeue(out handler))
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
640 // if the promise have been resolved while we was adding handler to the queue
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
641 // we can't guarantee that someone is still processing it
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
642 // therefore we will fetch a handler from the queue and execute it
27
cin
parents: 26
diff changeset
643 // note that fetched handler may be not the one that we have added
cin
parents: 26
diff changeset
644 // even we can fetch no handlers at all :)
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
645 InvokeHandler(handler);
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
646 }
2
aa367305156b small fixes
cin
parents: 1
diff changeset
647
106
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
648 protected virtual void InvokeHandler(AbstractHandler handler) {
10
aa33d0bb8c0c implemeted new cancellable promises concept
cin
parents: 9
diff changeset
649 switch (m_state) {
71
1714fd8678ef code cleanup
cin
parents: 66
diff changeset
650 case SUCCEEDED_STATE:
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
651 handler.Resolve(m_result);
10
aa33d0bb8c0c implemeted new cancellable promises concept
cin
parents: 9
diff changeset
652 break;
71
1714fd8678ef code cleanup
cin
parents: 66
diff changeset
653 case REJECTED_STATE:
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
654 handler.Reject(m_error);
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
655 break;
71
1714fd8678ef code cleanup
cin
parents: 66
diff changeset
656 case CANCELLED_STATE:
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
657 handler.Cancel();
10
aa33d0bb8c0c implemeted new cancellable promises concept
cin
parents: 9
diff changeset
658 break;
aa33d0bb8c0c implemeted new cancellable promises concept
cin
parents: 9
diff changeset
659 default:
aa33d0bb8c0c implemeted new cancellable promises concept
cin
parents: 9
diff changeset
660 // do nothing
aa33d0bb8c0c implemeted new cancellable promises concept
cin
parents: 9
diff changeset
661 return;
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
662 }
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
663 }
2
aa367305156b small fixes
cin
parents: 1
diff changeset
664
65
653c4e04968b minor changes
cin
parents: 33
diff changeset
665 void OnStateChanged() {
106
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
666 AbstractHandler handler;
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
667 while (m_handlers.TryDequeue(out handler))
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
668 InvokeHandler(handler);
11
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
669 }
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
670
9
cin
parents: 7
diff changeset
671 public bool IsExclusive {
cin
parents: 7
diff changeset
672 get {
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
673 return m_childrenCount <= 1;
9
cin
parents: 7
diff changeset
674 }
cin
parents: 7
diff changeset
675 }
cin
parents: 7
diff changeset
676
25
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
677 /// <summary>
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
678 /// Объединяет несколько обещаний в одно, результатом которого является массив результатов других обещаний.
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
679 /// Если хотябы одно из переданных обещаний не будет выполнено, то новое обещение тоже не будет выполнено.
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
680 /// При отмене нового обещания, переданные обещания также будут отменены, если никто больше на них не подписан.
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
681 /// </summary>
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
682 /// <param name="promises">Список обещаний. Если список пустой, то результирующее обещание возвращается уже выполненным.</param>
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
683 /// <returns>Обещание объединяющее в себе результат переданных обещаний.</returns>
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
684 /// <exception cref="ArgumentNullException"><paramref name="promises"/> не может быть null</exception>
30
2fad2d1f4b03 small refactoring, cleanup.
cin
parents: 29
diff changeset
685 public static IPromise<T[]> CreateComposite(IList<IPromise<T>> promises) {
25
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
686 if (promises == null)
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
687 throw new ArgumentNullException();
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
688
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
689 // создаем аккумулятор для результатов и результирующее обещание
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
690 var result = new T[promises.Count];
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
691 var promise = new Promise<T[]>();
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
692
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
693 // special case
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
694 if (promises.Count == 0) {
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
695 promise.Resolve(result);
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
696 return promise;
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
697 }
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
698
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
699 int pending = promises.Count;
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
700
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
701 for (int i = 0; i < promises.Count; i++) {
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
702 var dest = i;
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
703
33
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
704 if (promises[i] != null) {
106
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
705 promises[i].On(
33
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
706 x => {
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
707 result[dest] = x;
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
708 if (Interlocked.Decrement(ref pending) == 0)
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
709 promise.Resolve(result);
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
710 },
106
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
711 promise.Reject
33
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
712 );
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
713 } else {
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
714 if (Interlocked.Decrement(ref pending) == 0)
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
715 promise.Resolve(result);
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
716 }
25
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
717 }
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
718
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
719 promise.Cancelled(
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
720 () => {
33
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
721 foreach (var d in promises)
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
722 if (d != null && d.IsExclusive)
25
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
723 d.Cancel();
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
724 }
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
725 );
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
726
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
727 return promise;
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
728 }
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
729
33
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
730 /// <summary>
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
731 /// Объединяет несколько обещаний в одно. Результирующее обещание будет выполнено при
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
732 /// выполнении всех указанных обещаний. При этом возвращаемые значения первичных обещаний
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
733 /// игнорируются.
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
734 /// </summary>
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
735 /// <param name="promises">Коллекция первичных обещаний, которые будут объеденены в одно.</param>
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
736 /// <returns>Новое обещание, объединяющее в себе переданные.</returns>
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
737 /// <remarks>
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
738 /// Если в коллекции встречаюься <c>null</c>, то они воспринимаются как выполненные обещания.
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
739 /// </remarks>
66
790e8a997d30 Refactoring
cin
parents: 65
diff changeset
740 public static IPromise CreateComposite(ICollection<IPromise> promises) {
33
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
741 if (promises == null)
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
742 throw new ArgumentNullException();
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
743 if (promises.Count == 0)
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
744 return Promise<object>.ResultToPromise(null);
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
745
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
746 int countdown = promises.Count;
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
747
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
748 var result = new Promise<object>();
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
749
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
750 foreach (var d in promises) {
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
751 if (d == null) {
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
752 if (Interlocked.Decrement(ref countdown) == 0)
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
753 result.Resolve(null);
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
754 } else {
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
755 d.Then(() => {
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
756 if (Interlocked.Decrement(ref countdown) == 0)
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
757 result.Resolve(null);
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
758 });
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
759 }
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
760 }
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
761
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
762 result.Cancelled(() => {
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
763 foreach (var d in promises)
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
764 if (d != null && d.IsExclusive)
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
765 d.Cancel();
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
766 });
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
767
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
768 return result;
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
769 }
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
770
25
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
771 public static Promise<T> ResultToPromise(T result) {
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
772 var p = new Promise<T>();
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
773 p.Resolve(result);
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
774 return p;
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
775 }
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
776
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
777 public static Promise<T> ExceptionToPromise(Exception error) {
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
778 if (error == null)
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
779 throw new ArgumentNullException();
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
780
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
781 var p = new Promise<T>();
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
782 p.Reject(error);
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
783 return p;
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
784 }
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
785
33
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
786 #region IPromiseBase explicit implementation
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
787
101
279e226dffdd code cleanup
cin
parents: 99
diff changeset
788 IPromise IPromise.Then(Action success, Action<Exception> error, Action cancel) {
76
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
789 return Then(
106
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
790 success != null ? new Func<T,T>(x => {
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
791 success();
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
792 return x;
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
793 }) : null,
101
279e226dffdd code cleanup
cin
parents: 99
diff changeset
794 error != null ? new Func<Exception,T>(e => {
76
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
795 error(e);
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
796 return default(T);
96
daffa72a1cec Added the chaining method to the non-generic IPromise
cin
parents: 80
diff changeset
797 }) : null,
76
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
798 cancel
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
799 );
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
800 }
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
801
101
279e226dffdd code cleanup
cin
parents: 99
diff changeset
802 IPromise IPromise.Then(Action success, Action<Exception> error) {
76
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
803 return Then(
106
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
804 success != null ? new Func<T,T>(x => {
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
805 success();
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
806 return x;
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
807 }) : null,
101
279e226dffdd code cleanup
cin
parents: 99
diff changeset
808 error != null ? new Func<Exception,T>(e => {
76
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
809 error(e);
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
810 return default(T);
96
daffa72a1cec Added the chaining method to the non-generic IPromise
cin
parents: 80
diff changeset
811 }) : null
76
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
812 );
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
813 }
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
814
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
815 IPromise IPromise.Then(Action success) {
96
daffa72a1cec Added the chaining method to the non-generic IPromise
cin
parents: 80
diff changeset
816 Safe.ArgumentNotNull(success, "success");
106
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
817 return Then(x => {
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
818 success();
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
819 return x;
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
820 });
76
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
821 }
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
822
101
279e226dffdd code cleanup
cin
parents: 99
diff changeset
823 IPromise IPromise.Chain(Func<IPromise> chained, Func<Exception,IPromise> error, Action cancel) {
96
daffa72a1cec Added the chaining method to the non-generic IPromise
cin
parents: 80
diff changeset
824 return ChainNoResult(chained, error, cancel);
daffa72a1cec Added the chaining method to the non-generic IPromise
cin
parents: 80
diff changeset
825 }
daffa72a1cec Added the chaining method to the non-generic IPromise
cin
parents: 80
diff changeset
826
101
279e226dffdd code cleanup
cin
parents: 99
diff changeset
827 IPromise ChainNoResult(Func<IPromise> chained, Func<Exception,IPromise> error, Action cancel) {
104
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
828 Safe.ArgumentNotNull(chained, "chained");
96
daffa72a1cec Added the chaining method to the non-generic IPromise
cin
parents: 80
diff changeset
829
101
279e226dffdd code cleanup
cin
parents: 99
diff changeset
830 var medium = new Promise<object>(this);
96
daffa72a1cec Added the chaining method to the non-generic IPromise
cin
parents: 80
diff changeset
831
106
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
832 Func<T,T> resultHandler = delegate {
104
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
833 if (medium.IsCancelled)
106
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
834 return default(T);
96
daffa72a1cec Added the chaining method to the non-generic IPromise
cin
parents: 80
diff changeset
835
104
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
836 var promise = chained();
96
daffa72a1cec Added the chaining method to the non-generic IPromise
cin
parents: 80
diff changeset
837
104
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
838 promise.On(
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
839 medium.Resolve,
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
840 medium.Reject,
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
841 () => medium.Reject(new OperationCanceledException()) // внешняя отмена связанной операции рассматривается как ошибка
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
842 );
96
daffa72a1cec Added the chaining method to the non-generic IPromise
cin
parents: 80
diff changeset
843
104
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
844 // notify chained operation that it's not needed anymore
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
845 // порядок вызова Then, Cancelled важен, поскольку от этого
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
846 // зависит IsExclusive
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
847 medium.Cancelled(() => {
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
848 if (promise.IsExclusive)
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
849 promise.Cancel();
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
850 });
106
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
851
d4e38929ce36 promises refactoring
cin
parents: 105
diff changeset
852 return default(T);
104
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
853 };
96
daffa72a1cec Added the chaining method to the non-generic IPromise
cin
parents: 80
diff changeset
854
101
279e226dffdd code cleanup
cin
parents: 99
diff changeset
855 Func<Exception,T> errorHandler;
96
daffa72a1cec Added the chaining method to the non-generic IPromise
cin
parents: 80
diff changeset
856
104
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
857 if (error != null)
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
858 errorHandler = delegate(Exception e) {
96
daffa72a1cec Added the chaining method to the non-generic IPromise
cin
parents: 80
diff changeset
859 try {
daffa72a1cec Added the chaining method to the non-generic IPromise
cin
parents: 80
diff changeset
860 var promise = error(e);
daffa72a1cec Added the chaining method to the non-generic IPromise
cin
parents: 80
diff changeset
861
104
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
862 promise.On(
96
daffa72a1cec Added the chaining method to the non-generic IPromise
cin
parents: 80
diff changeset
863 medium.Resolve,
daffa72a1cec Added the chaining method to the non-generic IPromise
cin
parents: 80
diff changeset
864 medium.Reject,
daffa72a1cec Added the chaining method to the non-generic IPromise
cin
parents: 80
diff changeset
865 () => medium.Reject(new OperationCanceledException()) // внешняя отмена связанной операции рассматривается как ошибка
daffa72a1cec Added the chaining method to the non-generic IPromise
cin
parents: 80
diff changeset
866 );
daffa72a1cec Added the chaining method to the non-generic IPromise
cin
parents: 80
diff changeset
867
daffa72a1cec Added the chaining method to the non-generic IPromise
cin
parents: 80
diff changeset
868 // notify chained operation that it's not needed anymore
daffa72a1cec Added the chaining method to the non-generic IPromise
cin
parents: 80
diff changeset
869 // порядок вызова Then, Cancelled важен, поскольку от этого
daffa72a1cec Added the chaining method to the non-generic IPromise
cin
parents: 80
diff changeset
870 // зависит IsExclusive
daffa72a1cec Added the chaining method to the non-generic IPromise
cin
parents: 80
diff changeset
871 medium.Cancelled(() => {
daffa72a1cec Added the chaining method to the non-generic IPromise
cin
parents: 80
diff changeset
872 if (promise.IsExclusive)
daffa72a1cec Added the chaining method to the non-generic IPromise
cin
parents: 80
diff changeset
873 promise.Cancel();
daffa72a1cec Added the chaining method to the non-generic IPromise
cin
parents: 80
diff changeset
874 });
daffa72a1cec Added the chaining method to the non-generic IPromise
cin
parents: 80
diff changeset
875 } catch (Exception e2) {
daffa72a1cec Added the chaining method to the non-generic IPromise
cin
parents: 80
diff changeset
876 medium.Reject(e2);
daffa72a1cec Added the chaining method to the non-generic IPromise
cin
parents: 80
diff changeset
877 }
daffa72a1cec Added the chaining method to the non-generic IPromise
cin
parents: 80
diff changeset
878 return default(T);
daffa72a1cec Added the chaining method to the non-generic IPromise
cin
parents: 80
diff changeset
879 };
104
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
880 else
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
881 errorHandler = err => {
96
daffa72a1cec Added the chaining method to the non-generic IPromise
cin
parents: 80
diff changeset
882 medium.Reject(err);
daffa72a1cec Added the chaining method to the non-generic IPromise
cin
parents: 80
diff changeset
883 return default(T);
daffa72a1cec Added the chaining method to the non-generic IPromise
cin
parents: 80
diff changeset
884 };
daffa72a1cec Added the chaining method to the non-generic IPromise
cin
parents: 80
diff changeset
885
daffa72a1cec Added the chaining method to the non-generic IPromise
cin
parents: 80
diff changeset
886
104
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
887 Action cancelHandler;
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
888 if (cancel != null)
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
889 cancelHandler = () => {
96
daffa72a1cec Added the chaining method to the non-generic IPromise
cin
parents: 80
diff changeset
890 if (cancel != null)
daffa72a1cec Added the chaining method to the non-generic IPromise
cin
parents: 80
diff changeset
891 cancel();
daffa72a1cec Added the chaining method to the non-generic IPromise
cin
parents: 80
diff changeset
892 medium.Cancel();
daffa72a1cec Added the chaining method to the non-generic IPromise
cin
parents: 80
diff changeset
893 };
104
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
894 else
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
895 cancelHandler = medium.Cancel;
96
daffa72a1cec Added the chaining method to the non-generic IPromise
cin
parents: 80
diff changeset
896
107
f5220e5472ef minor fixes and optimizations
cin
parents: 106
diff changeset
897 AddMappers(
104
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
898 resultHandler,
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
899 errorHandler,
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
900 cancelHandler,
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
901 null,
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
902 true
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
903 );
96
daffa72a1cec Added the chaining method to the non-generic IPromise
cin
parents: 80
diff changeset
904
104
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
905 return medium;
96
daffa72a1cec Added the chaining method to the non-generic IPromise
cin
parents: 80
diff changeset
906 }
104
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
907
101
279e226dffdd code cleanup
cin
parents: 99
diff changeset
908 IPromise IPromise.Chain(Func<IPromise> chained, Func<Exception,IPromise> error) {
96
daffa72a1cec Added the chaining method to the non-generic IPromise
cin
parents: 80
diff changeset
909 return ChainNoResult(chained, error, null);
daffa72a1cec Added the chaining method to the non-generic IPromise
cin
parents: 80
diff changeset
910 }
104
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
911
96
daffa72a1cec Added the chaining method to the non-generic IPromise
cin
parents: 80
diff changeset
912 IPromise IPromise.Chain(Func<IPromise> chained) {
daffa72a1cec Added the chaining method to the non-generic IPromise
cin
parents: 80
diff changeset
913 return ChainNoResult(chained, null, null);
104
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
914 }
96
daffa72a1cec Added the chaining method to the non-generic IPromise
cin
parents: 80
diff changeset
915
daffa72a1cec Added the chaining method to the non-generic IPromise
cin
parents: 80
diff changeset
916
104
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
917 void IPromise.On(Action success, Action<Exception> error, Action cancel) {
105
4d308952fd5e minor fixes
cin
parents: 104
diff changeset
918 On(success != null ? new Action<T>(x => success()) : null, error, cancel);
76
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
919 }
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
920
104
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
921 void IPromise.On(Action success, Action<Exception> error) {
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
922 On(x => success(), error, null);
76
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
923 }
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
924
104
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
925 void IPromise.On(Action success) {
5f10d54b45df renamed Promise.Last -> Promise.On
cin
parents: 101
diff changeset
926 On(x => success(), null, null);
76
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
927 }
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
928
101
279e226dffdd code cleanup
cin
parents: 99
diff changeset
929 IPromise IPromise.Error(Action<Exception> error) {
33
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
930 return Error(error);
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
931 }
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
932
76
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
933 IPromise IPromise.Anyway(Action handler) {
c761fc982e1d Refactoring of the IPromise<T> interface
cin
parents: 75
diff changeset
934 return Anyway(handler);
33
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
935 }
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
936
66
790e8a997d30 Refactoring
cin
parents: 65
diff changeset
937 IPromise IPromise.Cancelled(Action handler) {
33
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
938 return Cancelled(handler);
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
939 }
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
940
66
790e8a997d30 Refactoring
cin
parents: 65
diff changeset
941 void IPromise.Join() {
33
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
942 Join();
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
943 }
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
944
66
790e8a997d30 Refactoring
cin
parents: 65
diff changeset
945 void IPromise.Join(int timeout) {
33
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
946 Join(timeout);
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
947 }
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
948
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
949 #endregion
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
950
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
951
b255e4aeef17 removed the reference to the parent from the promise object this allows
cin
parents: 32
diff changeset
952
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
953 }
2
aa367305156b small fixes
cin
parents: 1
diff changeset
954 }