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