Mercurial > pub > ImplabNet
annotate Implab/Promise.cs @ 115:ffd3702968c7 v2
fixed JSON writer
author | cin |
---|---|
date | Sun, 21 Dec 2014 13:52:08 +0300 |
parents | 38d6a4db35d7 |
children | 2573b562e328 |
rev | line source |
---|---|
2 | 1 using System; |
2 using System.Collections.Generic; | |
3 using System.Reflection; | |
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 | 6 |
7 namespace Implab { | |
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 | 43 public class Promise<T> : IPromise<T> { |
2 | 44 |
106 | 45 protected abstract class AbstractHandler : MTCustomQueueNode<AbstractHandler> { |
46 public abstract void Resolve(T result); | |
47 public abstract void Reject(Exception error); | |
48 public abstract void Cancel(); | |
49 } | |
50 | |
107 | 51 protected class RemapDescriptor<T2> : AbstractHandler { |
106 | 52 |
53 readonly Func<T,T2> m_resultHandler; | |
54 readonly Func<Exception,T2> m_errorHandler; | |
55 readonly Action m_cancellHandler; | |
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 | 58 public RemapDescriptor(Func<T,T2> resultHandler, Func<Exception,T2> errorHandler, Action cancelHandler, Promise<T2> medium) { |
106 | 59 m_resultHandler = resultHandler; |
60 m_errorHandler = errorHandler; | |
61 m_cancellHandler = cancelHandler; | |
62 m_medium = medium; | |
63 } | |
64 | |
65 public override void Resolve(T result) { | |
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 | 68 if (m_medium != null) |
69 m_medium.Resolve(m_resultHandler(result)); | |
70 else | |
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 | 75 } else if(m_medium != null) |
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 | 79 public override void Reject(Exception error) { |
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 | 82 var res = m_errorHandler(error); |
83 if (m_medium != null) | |
84 m_medium.Resolve(res); | |
107 | 85 } catch (Exception err2) { |
86 if (m_medium != null) | |
87 m_medium.Reject(err2); | |
88 } | |
89 } else if (m_medium != null) | |
90 m_medium.Reject(error); | |
91 } | |
92 | |
93 public override void Cancel() { | |
94 if (m_cancellHandler != null) { | |
95 try { | |
96 m_cancellHandler(); | |
97 } catch (Exception err) { | |
98 Reject(err); | |
99 return; | |
100 } | |
101 } | |
102 if (m_medium != null) | |
103 m_medium.Cancel(); | |
104 } | |
105 } | |
106 | |
107 protected class HandlerDescriptor : AbstractHandler { | |
108 | |
109 readonly Action<T> m_resultHandler; | |
110 readonly Action<Exception> m_errorHandler; | |
111 readonly Action m_cancellHandler; | |
112 readonly Promise<T> m_medium; | |
113 | |
114 public HandlerDescriptor(Action<T> resultHandler, Action<Exception> errorHandler, Action cancelHandler, Promise<T> medium) { | |
115 m_resultHandler = resultHandler; | |
116 m_errorHandler = errorHandler; | |
117 m_cancellHandler = cancelHandler; | |
118 m_medium = medium; | |
119 } | |
120 | |
121 public override void Resolve(T result) { | |
122 if (m_resultHandler != null) { | |
123 try { | |
124 m_resultHandler(result); | |
125 } catch (Exception e) { | |
126 Reject(e); | |
127 return; | |
128 } | |
129 } | |
130 if(m_medium != null) | |
131 m_medium.Resolve(result); | |
132 } | |
133 | |
134 public override void Reject(Exception error) { | |
135 if (m_errorHandler != null) { | |
136 try { | |
137 m_errorHandler(error); | |
138 if (m_medium != null) | |
139 m_medium.Resolve(default(T)); | |
72 | 140 } catch (Exception err2) { |
106 | 141 if (m_medium != null) |
142 m_medium.Reject(err2); | |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
143 } |
106 | 144 } else if (m_medium != null) |
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 | 148 public override void Cancel() { |
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 | 151 m_cancellHandler(); |
72 | 152 } catch (Exception err) { |
153 Reject(err); | |
154 return; | |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
155 } |
72 | 156 } |
106 | 157 if (m_medium != null) |
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 | 162 const int UNRESOLVED_SATE = 0; |
163 const int TRANSITIONAL_STATE = 1; | |
164 const int SUCCEEDED_STATE = 2; | |
165 const int REJECTED_STATE = 3; | |
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 | 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 | 172 |
106 | 173 readonly MTCustomQueue<AbstractHandler> m_handlers = new MTCustomQueue<AbstractHandler>(); |
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 | 178 |
101 | 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) |
112 | 181 AddHandler( |
76 | 182 null, |
183 null, | |
184 () => { | |
185 if (parent.IsExclusive) | |
186 parent.Cancel(); | |
187 }, | |
104 | 188 null, |
189 false | |
76 | 190 ); |
10 | 191 } |
2 | 192 |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
193 bool BeginTransit() { |
71 | 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 | 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 | 202 void WaitTransition() { |
71 | 203 while (m_state == TRANSITIONAL_STATE) { |
80 | 204 Thread.MemoryBarrier(); |
25 | 205 } |
206 } | |
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 | 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 | 217 Thread.MemoryBarrier(); |
71 | 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 | 222 public Type PromiseType { |
223 get { return typeof(T); } | |
224 } | |
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 | 234 CompleteTransit(SUCCEEDED_STATE); |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
235 OnStateChanged(); |
25 | 236 } else { |
237 WaitTransition(); | |
71 | 238 if (m_state != CANCELLED_STATE) |
25 | 239 throw new InvalidOperationException("The promise is already resolved"); |
240 } | |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
241 } |
2 | 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 | 256 /// <remarks> |
257 /// Поскольку обещание должно работать в многопточной среде, при его выполнении сразу несколько потоков | |
258 /// могу вернуть ошибку, при этом только первая будет использована в качестве результата, остальные | |
259 /// будут проигнорированы. | |
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 | 265 m_error = error is TransientPromiseException ? error.InnerException : error; |
71 | 266 CompleteTransit(REJECTED_STATE); |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
267 OnStateChanged(); |
25 | 268 } else { |
269 WaitTransition(); | |
71 | 270 if (m_state == SUCCEEDED_STATE) |
25 | 271 throw new InvalidOperationException("The promise is already resolved"); |
272 } | |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
273 } |
2 | 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 | 278 /// <remarks>Для определения была ли операция отменена следует использовать свойство <see cref="IsCancelled"/>.</remarks> |
279 public void Cancel() { | |
101 | 280 if (BeginTransit()) { |
71 | 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 | 286 /// <summary> |
287 /// Последний обработчик в цепочки обещаний. | |
288 /// </summary> | |
289 /// <param name="success"></param> | |
290 /// <param name="error"></param> | |
291 /// <param name="cancel"></param> | |
292 /// <remarks> | |
293 /// <para> | |
294 /// Данный метод не создает связанного с текущим обещания и предназначен для окончания | |
295 /// фсинхронной цепочки. | |
296 /// </para> | |
297 /// <para> | |
298 /// Если данный метод вызвать несколько раз, либо добавить другие обработчики, то цепочка | |
299 /// не будет одиночной <see cref="IsExclusive"/> и, как следствие, будет невозможна отмена | |
300 /// всей цепи обещаний снизу (с самого последнего обещания). | |
301 /// </para> | |
302 /// </remarks> | |
104 | 303 public void On(Action<T> success, Action<Exception> error, Action cancel) { |
75 | 304 if (success == null && error == null && cancel == null) |
305 return; | |
306 | |
107 | 307 AddHandler(success, error, cancel, null, false); |
104 | 308 } |
309 | |
310 public void On(Action<T> success, Action<Exception> error) { | |
107 | 311 AddHandler(success, error, null, null, false); |
104 | 312 } |
313 | |
314 public void On(Action<T> success) { | |
107 | 315 AddHandler(success, null, null, null, false); |
75 | 316 } |
317 | |
104 | 318 public void On(Action handler, PromiseEventType events) { |
319 Safe.ArgumentNotNull(handler, "handler"); | |
75 | 320 |
104 | 321 |
107 | 322 AddHandler( |
323 events.HasFlag(PromiseEventType.Success) ? new Action<T>(x => handler()) : null, | |
324 events.HasFlag(PromiseEventType.Error) ? new Action<Exception>( x => handler()) : null, | |
325 events.HasFlag(PromiseEventType.Cancelled) ? handler : null, | |
326 null, | |
327 false | |
328 ); | |
75 | 329 } |
330 | |
101 | 331 public IPromise Error(Action<Exception> error) { |
72 | 332 if (error == null) |
333 return this; | |
334 | |
101 | 335 var medium = new Promise<T>(this); |
72 | 336 |
107 | 337 AddMappers( |
112 | 338 x => x, |
72 | 339 e => { |
340 error(e); | |
341 return default(T); | |
342 }, | |
343 null, | |
104 | 344 medium, |
345 true | |
72 | 346 ); |
347 | |
348 return medium; | |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
349 } |
2 | 350 |
11 | 351 /// <summary> |
352 /// Handles error and allows to keep the promise. | |
353 /// </summary> | |
354 /// <remarks> | |
355 /// If the specified handler throws an exception, this exception will be used to reject the promise. | |
356 /// </remarks> | |
357 /// <param name="handler">The error handler which returns the result of the promise.</param> | |
358 /// <returns>New promise.</returns> | |
101 | 359 public IPromise<T> Error(Func<Exception,T> handler) { |
11 | 360 if (handler == null) |
361 return this; | |
362 | |
101 | 363 var medium = new Promise<T>(this); |
11 | 364 |
112 | 365 AddMappers(x => x, handler, null, medium, true); |
11 | 366 |
367 return medium; | |
368 } | |
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 | 378 /// <param name = "cancel"></param> |
101 | 379 public IPromise<TNew> Then<TNew>(Func<T, TNew> mapper, Func<Exception,TNew> error, Action cancel) { |
76 | 380 Safe.ArgumentNotNull(mapper, "mapper"); |
381 | |
382 // создаем прицепленное обещание | |
101 | 383 var medium = new Promise<TNew>(this); |
2 | 384 |
107 | 385 AddMappers( |
106 | 386 mapper, |
387 error, | |
388 cancel, | |
389 medium, | |
104 | 390 true |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
391 ); |
2 | 392 |
76 | 393 return medium; |
394 } | |
395 | |
101 | 396 public IPromise<TNew> Then<TNew>(Func<T, TNew> mapper, Func<Exception,TNew> error) { |
76 | 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 | 400 public IPromise<TNew> Then<TNew>(Func<T, TNew> mapper) { |
76 | 401 return Then(mapper, null, null); |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
402 } |
2 | 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 | 414 /// <param name = "cancel"></param> |
101 | 415 public IPromise<TNew> Chain<TNew>(Func<T, IPromise<TNew>> chained, Func<Exception,IPromise<TNew>> error, Action cancel) { |
76 | 416 |
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 | 423 var medium = new Promise<TNew>(this); |
2 | 424 |
106 | 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 | 427 return default(T); |
10 | 428 |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
429 var promise = chained(result); |
10 | 430 |
104 | 431 promise.On( |
72 | 432 medium.Resolve, |
76 | 433 medium.Reject, |
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 | 440 medium.On( |
101 | 441 null, |
442 null, | |
443 () => { | |
444 if (promise.IsExclusive) | |
445 promise.Cancel(); | |
446 } | |
447 ); | |
106 | 448 |
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 | 452 Func<Exception,T> errorHandler; |
76 | 453 |
454 if (error != null) | |
455 errorHandler = delegate(Exception e) { | |
72 | 456 try { |
76 | 457 var promise = error(e); |
458 | |
104 | 459 promise.On( |
76 | 460 medium.Resolve, |
461 medium.Reject, | |
462 () => medium.Reject(new OperationCanceledException()) // внешняя отмена связанной операции рассматривается как ошибка | |
463 ); | |
464 | |
465 // notify chained operation that it's not needed anymore | |
466 // порядок вызова Then, Cancelled важен, поскольку от этого | |
467 // зависит IsExclusive | |
468 medium.Cancelled(() => { | |
469 if (promise.IsExclusive) | |
470 promise.Cancel(); | |
471 }); | |
72 | 472 } catch (Exception e2) { |
473 medium.Reject(e2); | |
474 } | |
76 | 475 return default(T); |
476 }; | |
477 else | |
478 errorHandler = err => { | |
479 medium.Reject(err); | |
480 return default(T); | |
481 }; | |
482 | |
483 | |
484 Action cancelHandler; | |
485 if (cancel != null) | |
486 cancelHandler = () => { | |
487 if (cancel != null) | |
488 cancel(); | |
489 medium.Cancel(); | |
490 }; | |
491 else | |
492 cancelHandler = medium.Cancel; | |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
493 |
107 | 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 | 497 cancelHandler, |
104 | 498 null, |
499 true | |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
500 ); |
2 | 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 | 505 public IPromise<TNew> Chain<TNew>(Func<T, IPromise<TNew>> chained, Func<Exception,IPromise<TNew>> error) { |
76 | 506 return Chain(chained, error, null); |
507 } | |
508 | |
101 | 509 public IPromise<TNew> Chain<TNew>(Func<T, IPromise<TNew>> chained) { |
76 | 510 return Chain(chained, null, null); |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
511 } |
2 | 512 |
26 | 513 public IPromise<T> Cancelled(Action handler) { |
101 | 514 var medium = new Promise<T>(this); |
104 | 515 AddHandler(null, null, handler, medium, false); |
74 | 516 return medium; |
10 | 517 } |
518 | |
25 | 519 /// <summary> |
520 /// Adds the specified handler for all cases (success, error, cancel) | |
521 /// </summary> | |
522 /// <param name="handler">The handler that will be called anyway</param> | |
523 /// <returns>self</returns> | |
76 | 524 public IPromise<T> Anyway(Action handler) { |
525 Safe.ArgumentNotNull(handler, "handler"); | |
104 | 526 |
527 var medium = new Promise<T>(this); | |
528 | |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
529 AddHandler( |
107 | 530 x => handler(), |
72 | 531 e => { |
532 handler(); | |
533 throw new TransientPromiseException(e); | |
534 }, | |
535 handler, | |
104 | 536 medium, |
537 true | |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
538 ); |
104 | 539 |
540 return medium; | |
10 | 541 } |
542 | |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
543 /// <summary> |
29 | 544 /// Преобразует результат обещания к нужному типу |
545 /// </summary> | |
546 /// <typeparam name="T2"></typeparam> | |
547 /// <returns></returns> | |
548 public IPromise<T2> Cast<T2>() { | |
75 | 549 return Then(x => (T2)(object)x, null); |
29 | 550 } |
551 | |
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 | 574 var evt = new ManualResetEvent(false); |
76 | 575 Anyway(() => evt.Set()); |
2 | 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 | 579 |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
580 switch (m_state) { |
71 | 581 case SUCCEEDED_STATE: |
10 | 582 return m_result; |
71 | 583 case CANCELLED_STATE: |
10 | 584 throw new OperationCanceledException(); |
71 | 585 case REJECTED_STATE: |
10 | 586 throw new TargetInvocationException(m_error); |
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 | 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 | 595 |
107 | 596 void AddMappers<T2>(Func<T,T2> success, Func<Exception,T2> error, Action cancel, Promise<T2> medium, bool inc) { |
104 | 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 | 600 AbstractHandler handler = new RemapDescriptor<T2>(success, error, cancel, medium); |
601 | |
602 bool queued; | |
603 | |
604 if (!IsResolved) { | |
605 m_handlers.Enqueue(handler); | |
606 queued = true; | |
607 } else { | |
608 // the promise is in resolved state, just invoke the handled with minimum overhead | |
609 queued = false; | |
610 InvokeHandler(handler); | |
611 } | |
612 | |
613 if (queued && IsResolved && m_handlers.TryDequeue(out handler)) | |
614 // if the promise have been resolved while we was adding handler to the queue | |
615 // we can't guarantee that someone is still processing it | |
616 // therefore we will fetch a handler from the queue and execute it | |
617 // note that fetched handler may be not the one that we have added | |
618 // even we can fetch no handlers at all :) | |
619 InvokeHandler(handler); | |
620 } | |
621 | |
622 void AddHandler(Action<T> success, Action<Exception> error, Action cancel, Promise<T> medium, bool inc) { | |
623 if (inc) | |
624 Interlocked.Increment(ref m_childrenCount); | |
625 | |
626 AbstractHandler handler = new HandlerDescriptor(success, error, cancel, medium); | |
2 | 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 | 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 | 643 // note that fetched handler may be not the one that we have added |
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 | 647 |
106 | 648 protected virtual void InvokeHandler(AbstractHandler handler) { |
10 | 649 switch (m_state) { |
71 | 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 | 652 break; |
71 | 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 | 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 | 658 break; |
659 default: | |
660 // do nothing | |
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 | 664 |
65 | 665 void OnStateChanged() { |
106 | 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 | 669 } |
670 | |
9 | 671 public bool IsExclusive { |
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 | 674 } |
675 } | |
676 | |
25 | 677 /// <summary> |
678 /// Объединяет несколько обещаний в одно, результатом которого является массив результатов других обещаний. | |
679 /// Если хотябы одно из переданных обещаний не будет выполнено, то новое обещение тоже не будет выполнено. | |
680 /// При отмене нового обещания, переданные обещания также будут отменены, если никто больше на них не подписан. | |
681 /// </summary> | |
682 /// <param name="promises">Список обещаний. Если список пустой, то результирующее обещание возвращается уже выполненным.</param> | |
683 /// <returns>Обещание объединяющее в себе результат переданных обещаний.</returns> | |
684 /// <exception cref="ArgumentNullException"><paramref name="promises"/> не может быть null</exception> | |
30 | 685 public static IPromise<T[]> CreateComposite(IList<IPromise<T>> promises) { |
25 | 686 if (promises == null) |
687 throw new ArgumentNullException(); | |
688 | |
689 // создаем аккумулятор для результатов и результирующее обещание | |
690 var result = new T[promises.Count]; | |
691 var promise = new Promise<T[]>(); | |
692 | |
693 // special case | |
694 if (promises.Count == 0) { | |
695 promise.Resolve(result); | |
696 return promise; | |
697 } | |
698 | |
699 int pending = promises.Count; | |
700 | |
701 for (int i = 0; i < promises.Count; i++) { | |
702 var dest = i; | |
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 | 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 | 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 | 717 } |
718 | |
719 promise.Cancelled( | |
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 | 723 d.Cancel(); |
724 } | |
725 ); | |
726 | |
727 return promise; | |
728 } | |
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 | 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 | 771 public static Promise<T> ResultToPromise(T result) { |
772 var p = new Promise<T>(); | |
773 p.Resolve(result); | |
774 return p; | |
775 } | |
776 | |
777 public static Promise<T> ExceptionToPromise(Exception error) { | |
778 if (error == null) | |
779 throw new ArgumentNullException(); | |
780 | |
781 var p = new Promise<T>(); | |
782 p.Reject(error); | |
783 return p; | |
784 } | |
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 | 788 IPromise IPromise.Then(Action success, Action<Exception> error, Action cancel) { |
76 | 789 return Then( |
106 | 790 success != null ? new Func<T,T>(x => { |
791 success(); | |
792 return x; | |
793 }) : null, | |
101 | 794 error != null ? new Func<Exception,T>(e => { |
76 | 795 error(e); |
796 return default(T); | |
96 | 797 }) : null, |
76 | 798 cancel |
799 ); | |
800 } | |
801 | |
101 | 802 IPromise IPromise.Then(Action success, Action<Exception> error) { |
76 | 803 return Then( |
106 | 804 success != null ? new Func<T,T>(x => { |
805 success(); | |
806 return x; | |
807 }) : null, | |
101 | 808 error != null ? new Func<Exception,T>(e => { |
76 | 809 error(e); |
810 return default(T); | |
96 | 811 }) : null |
76 | 812 ); |
813 } | |
814 | |
815 IPromise IPromise.Then(Action success) { | |
96 | 816 Safe.ArgumentNotNull(success, "success"); |
106 | 817 return Then(x => { |
818 success(); | |
819 return x; | |
820 }); | |
76 | 821 } |
822 | |
101 | 823 IPromise IPromise.Chain(Func<IPromise> chained, Func<Exception,IPromise> error, Action cancel) { |
96 | 824 return ChainNoResult(chained, error, cancel); |
825 } | |
826 | |
101 | 827 IPromise ChainNoResult(Func<IPromise> chained, Func<Exception,IPromise> error, Action cancel) { |
104 | 828 Safe.ArgumentNotNull(chained, "chained"); |
96 | 829 |
101 | 830 var medium = new Promise<object>(this); |
96 | 831 |
106 | 832 Func<T,T> resultHandler = delegate { |
104 | 833 if (medium.IsCancelled) |
106 | 834 return default(T); |
96 | 835 |
104 | 836 var promise = chained(); |
96 | 837 |
104 | 838 promise.On( |
839 medium.Resolve, | |
840 medium.Reject, | |
841 () => medium.Reject(new OperationCanceledException()) // внешняя отмена связанной операции рассматривается как ошибка | |
842 ); | |
96 | 843 |
104 | 844 // notify chained operation that it's not needed anymore |
845 // порядок вызова Then, Cancelled важен, поскольку от этого | |
846 // зависит IsExclusive | |
847 medium.Cancelled(() => { | |
848 if (promise.IsExclusive) | |
849 promise.Cancel(); | |
850 }); | |
106 | 851 |
852 return default(T); | |
104 | 853 }; |
96 | 854 |
101 | 855 Func<Exception,T> errorHandler; |
96 | 856 |
104 | 857 if (error != null) |
858 errorHandler = delegate(Exception e) { | |
96 | 859 try { |
860 var promise = error(e); | |
861 | |
104 | 862 promise.On( |
96 | 863 medium.Resolve, |
864 medium.Reject, | |
865 () => medium.Reject(new OperationCanceledException()) // внешняя отмена связанной операции рассматривается как ошибка | |
866 ); | |
867 | |
868 // notify chained operation that it's not needed anymore | |
869 // порядок вызова Then, Cancelled важен, поскольку от этого | |
870 // зависит IsExclusive | |
871 medium.Cancelled(() => { | |
872 if (promise.IsExclusive) | |
873 promise.Cancel(); | |
874 }); | |
875 } catch (Exception e2) { | |
876 medium.Reject(e2); | |
877 } | |
878 return default(T); | |
879 }; | |
104 | 880 else |
881 errorHandler = err => { | |
96 | 882 medium.Reject(err); |
883 return default(T); | |
884 }; | |
885 | |
886 | |
104 | 887 Action cancelHandler; |
888 if (cancel != null) | |
889 cancelHandler = () => { | |
96 | 890 if (cancel != null) |
891 cancel(); | |
892 medium.Cancel(); | |
893 }; | |
104 | 894 else |
895 cancelHandler = medium.Cancel; | |
96 | 896 |
107 | 897 AddMappers( |
104 | 898 resultHandler, |
899 errorHandler, | |
900 cancelHandler, | |
901 null, | |
902 true | |
903 ); | |
96 | 904 |
104 | 905 return medium; |
96 | 906 } |
104 | 907 |
101 | 908 IPromise IPromise.Chain(Func<IPromise> chained, Func<Exception,IPromise> error) { |
96 | 909 return ChainNoResult(chained, error, null); |
910 } | |
104 | 911 |
96 | 912 IPromise IPromise.Chain(Func<IPromise> chained) { |
913 return ChainNoResult(chained, null, null); | |
104 | 914 } |
96 | 915 |
916 | |
104 | 917 void IPromise.On(Action success, Action<Exception> error, Action cancel) { |
105 | 918 On(success != null ? new Action<T>(x => success()) : null, error, cancel); |
76 | 919 } |
920 | |
104 | 921 void IPromise.On(Action success, Action<Exception> error) { |
922 On(x => success(), error, null); | |
76 | 923 } |
924 | |
104 | 925 void IPromise.On(Action success) { |
926 On(x => success(), null, null); | |
76 | 927 } |
928 | |
101 | 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 | 933 IPromise IPromise.Anyway(Action handler) { |
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 | 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 | 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 | 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 | 954 } |