##// END OF EJS Templates
code cleanup...
cin -
r101:279e226dffdd v2
parent child
Show More
@@ -27,12 +27,12 namespace Implab {
27 27 /// </summary>
28 28 bool IsCancelled { get; }
29 29
30 IPromise Then(Action success, ErrorHandler error, Action cancel);
31 IPromise Then(Action success, ErrorHandler error);
30 IPromise Then(Action success, Action<Exception> error, Action cancel);
31 IPromise Then(Action success, Action<Exception> error);
32 32 IPromise Then(Action success);
33 33
34 IPromise Chain(Func<IPromise> chained, ErrorHandler<IPromise> error, Action cancel);
35 IPromise Chain(Func<IPromise> chained, ErrorHandler<IPromise> error);
34 IPromise Chain(Func<IPromise> chained, Func<Exception, IPromise> error, Action cancel);
35 IPromise Chain(Func<IPromise> chained, Func<Exception, IPromise> error);
36 36 IPromise Chain(Func<IPromise> chained);
37 37
38 38 /// <summary>
@@ -41,13 +41,13 namespace Implab {
41 41 /// <param name="success">Success.</param>
42 42 /// <param name="error">Error.</param>
43 43 /// <param name="cancel">Cancel.</param>
44 void Last(Action success, ErrorHandler error, Action cancel);
45 void Last(Action success, ErrorHandler error);
44 void Last(Action success, Action<Exception> error, Action cancel);
45 void Last(Action success, Action<Exception> error);
46 46 void Last(Action success);
47 47
48 IPromise Error(ErrorHandler error);
48 IPromise Error(Action<Exception> error);
49 49 /// <summary>
50 /// Обрабатывает либо ошибку, либо результат. Событие отмены не обрабатывается.
50 /// Обрабатывает либо ошибку, либо результат, либо отмену.
51 51 /// </summary>
52 52 /// <param name="handler">Обработчик.</param>
53 53 /// <remarks>После обработке ошибки, она передается дальше.</remarks>
@@ -58,9 +58,9 namespace Implab {
58 58 /// <remarks>После обработке ошибки, она передается дальше.</remarks>
59 59 IPromise Anyway(Action handler);
60 60 /// <summary>
61 /// Обработчик для регистрации отмены обещания, событие отмены не может быть подавлено.
61 /// Обработчик для регистрации отмены обещания.
62 62 /// </summary>
63 /// <returns>Новое обещание, связанное с текущим.</returns>
63 /// <returns>Новое обещание, связанное с текущим, выполнится после указанного обработчика.</returns>
64 64 /// <param name="handler">Обработчик события.</param>
65 65 /// <remarks>Если обработчик вызывает исключение, то оно передается обработчику ошибки, результат работы
66 66 /// которого будет передан связанному обещанию</remarks>
@@ -7,31 +7,31 namespace Implab {
7 7
8 8 new T Join(int timeout);
9 9
10 void Last(ResultHandler<T> success, ErrorHandler error, Action cancel);
10 void Last(Action<T> success, Action<Exception> error, Action cancel);
11 11
12 void Last(ResultHandler<T> success, ErrorHandler error);
12 void Last(Action<T> success, Action<Exception> error);
13 13
14 void Last(ResultHandler<T> success);
14 void Last(Action<T> success);
15 15
16 IPromise<T> Then(ResultHandler<T> success, ErrorHandler<T> error, Action cancel);
16 IPromise<T> Then(Action<T> success, Func<Exception,T> error, Action cancel);
17 17
18 IPromise<T> Then(ResultHandler<T> success, ErrorHandler<T> error);
18 IPromise<T> Then(Action<T> success, Func<Exception,T> error);
19 19
20 IPromise<T> Then(ResultHandler<T> success);
20 IPromise<T> Then(Action<T> success);
21 21
22 IPromise<T2> Then<T2>(ResultMapper<T, T2> mapper, ErrorHandler<T2> error, Action cancel);
22 IPromise<T2> Then<T2>(Func<T, T2> mapper, Func<Exception,T2> error, Action cancel);
23 23
24 IPromise<T2> Then<T2>(ResultMapper<T, T2> mapper, ErrorHandler<T2> error);
24 IPromise<T2> Then<T2>(Func<T, T2> mapper, Func<Exception,T2> error);
25 25
26 IPromise<T2> Then<T2>(ResultMapper<T, T2> mapper);
26 IPromise<T2> Then<T2>(Func<T, T2> mapper);
27 27
28 IPromise<T2> Chain<T2>(ResultMapper<T, IPromise<T2>> chained, ErrorHandler<IPromise<T2>> error, Action cancel);
28 IPromise<T2> Chain<T2>(Func<T, IPromise<T2>> chained, Func<Exception,IPromise<T2>> error, Action cancel);
29 29
30 IPromise<T2> Chain<T2>(ResultMapper<T, IPromise<T2>> chained, ErrorHandler<IPromise<T2>> error);
30 IPromise<T2> Chain<T2>(Func<T, IPromise<T2>> chained, Func<Exception,IPromise<T2>> error);
31 31
32 IPromise<T2> Chain<T2>(ResultMapper<T, IPromise<T2>> chained);
32 IPromise<T2> Chain<T2>(Func<T, IPromise<T2>> chained);
33 33
34 IPromise<T> Error(ErrorHandler<T> error);
34 IPromise<T> Error(Func<Exception,T> error);
35 35
36 36 new IPromise<T> Cancelled(Action handler);
37 37
@@ -1,9 +1,6
1 1 using Implab.Diagnostics;
2 2 using System;
3 using System.Collections.Generic;
4 3 using System.Diagnostics;
5 using System.Linq;
6 using System.Text;
7 4 using System.Threading;
8 5
9 6 namespace Implab.Parallels {
@@ -146,13 +143,13 namespace Implab.Parallels {
146 143 return iter.Promise;
147 144 }
148 145
149 public static IPromise<TDst[]> ChainedMap<TSrc, TDst>(this TSrc[] source, ResultMapper<TSrc, IPromise<TDst>> transform, int threads) {
146 public static IPromise<TDst[]> ChainedMap<TSrc, TDst>(this TSrc[] source, Func<TSrc, IPromise<TDst>> transform, int threads) {
150 147 if (source == null)
151 148 throw new ArgumentNullException("source");
152 149 if (transform == null)
153 150 throw new ArgumentNullException("transform");
154 151 if (threads <= 0)
155 throw new ArgumentOutOfRangeException("Threads number must be greater then zero");
152 throw new ArgumentOutOfRangeException("threads","Threads number must be greater then zero");
156 153
157 154 if (source.Length == 0)
158 155 return Promise<TDst[]>.ResultToPromise(new TDst[0]);
@@ -1,17 +1,11
1 1 using System;
2 2 using System.Collections.Generic;
3 3 using System.Reflection;
4 using System.Diagnostics;
5 4 using System.Threading;
6 5 using Implab.Parallels;
7 6
8 7 namespace Implab {
9 8
10 public delegate void ErrorHandler(Exception e);
11 public delegate T ErrorHandler<out T>(Exception e);
12 public delegate void ResultHandler<in T>(T result);
13 public delegate TNew ResultMapper<in TSrc,out TNew>(TSrc result);
14
15 9 /// <summary>
16 10 /// Класс для асинхронного получения результатов. Так называемое "обещание".
17 11 /// </summary>
@@ -49,8 +43,8 namespace Implab {
49 43 public class Promise<T> : IPromise<T> {
50 44
51 45 protected struct HandlerDescriptor {
52 public ResultHandler<T> resultHandler;
53 public ErrorHandler<T> errorHandler;
46 public Action<T> resultHandler;
47 public Func<Exception,T> errorHandler;
54 48 public Action cancellHandler;
55 49 public Promise<T> medium;
56 50
@@ -104,9 +98,7 namespace Implab {
104 98 const int REJECTED_STATE = 3;
105 99 const int CANCELLED_STATE = 4;
106 100
107 readonly bool m_cancellable;
108
109 int m_childrenCount = 0;
101 int m_childrenCount;
110 102 int m_state;
111 103 T m_result;
112 104 Exception m_error;
@@ -114,11 +106,9 namespace Implab {
114 106 readonly MTQueue<HandlerDescriptor> m_handlers = new MTQueue<HandlerDescriptor>();
115 107
116 108 public Promise() {
117 m_cancellable = true;
118 109 }
119 110
120 public Promise(IPromise parent, bool cancellable) {
121 m_cancellable = cancellable;
111 public Promise(IPromise parent) {
122 112 if (parent != null)
123 113 AddHandler(
124 114 null,
@@ -218,17 +208,17 namespace Implab {
218 208 /// </summary>
219 209 /// <remarks>Для определения была ли операция отменена следует использовать свойство <see cref="IsCancelled"/>.</remarks>
220 210 public void Cancel() {
221 if (m_cancellable && BeginTransit()) {
211 if (BeginTransit()) {
222 212 CompleteTransit(CANCELLED_STATE);
223 213 OnStateChanged();
224 214 }
225 215 }
226 216
227 public IPromise<T> Then(ResultHandler<T> success, ErrorHandler<T> error, Action cancel) {
217 public IPromise<T> Then(Action<T> success, Func<Exception,T> error, Action cancel) {
228 218 if (success == null && error == null && cancel == null)
229 219 return this;
230 220
231 var medium = new Promise<T>(this, true);
221 var medium = new Promise<T>(this);
232 222
233 223 AddHandler(success, error, cancel, medium);
234 224
@@ -242,11 +232,11 namespace Implab {
242 232 /// This handler will recieve an operation result as a parameter.</param>
243 233 /// <param name="error">Handles an exception that may occur during the operation and returns the value which will be used as the result of the operation.</param>
244 234 /// <returns>The new promise chained to this one.</returns>
245 public IPromise<T> Then(ResultHandler<T> success, ErrorHandler<T> error) {
235 public IPromise<T> Then(Action<T> success, Func<Exception,T> error) {
246 236 if (success == null && error == null)
247 237 return this;
248 238
249 var medium = new Promise<T>(this, true);
239 var medium = new Promise<T>(this);
250 240
251 241 AddHandler(success, error, null, medium);
252 242
@@ -256,11 +246,11 namespace Implab {
256 246
257 247
258 248
259 public IPromise<T> Then(ResultHandler<T> success) {
249 public IPromise<T> Then(Action<T> success) {
260 250 if (success == null)
261 251 return this;
262 252
263 var medium = new Promise<T>(this, true);
253 var medium = new Promise<T>(this);
264 254
265 255 AddHandler(success, null, null, medium);
266 256
@@ -284,11 +274,11 namespace Implab {
284 274 /// всей цепи обещаний снизу (с самого последнего обещания).
285 275 /// </para>
286 276 /// </remarks>
287 public void Last(ResultHandler<T> success, ErrorHandler error, Action cancel) {
277 public void Last(Action<T> success, Action<Exception> error, Action cancel) {
288 278 if (success == null && error == null && cancel == null)
289 279 return;
290 280
291 ErrorHandler<T> errorHandler = null;
281 Func<Exception,T> errorHandler = null;
292 282 if (error != null)
293 283 errorHandler = err => {
294 284 error(err);
@@ -297,19 +287,19 namespace Implab {
297 287 AddHandler(success, errorHandler, cancel, null);
298 288 }
299 289
300 public void Last(ResultHandler<T> success, ErrorHandler error) {
290 public void Last(Action<T> success, Action<Exception> error) {
301 291 Last(success, error, null);
302 292 }
303 293
304 public void Last(ResultHandler<T> success) {
294 public void Last(Action<T> success) {
305 295 Last(success, null, null);
306 296 }
307 297
308 public IPromise Error(ErrorHandler error) {
298 public IPromise Error(Action<Exception> error) {
309 299 if (error == null)
310 300 return this;
311 301
312 var medium = new Promise<T>(this, true);
302 var medium = new Promise<T>(this);
313 303
314 304 AddHandler(
315 305 null,
@@ -332,11 +322,11 namespace Implab {
332 322 /// </remarks>
333 323 /// <param name="handler">The error handler which returns the result of the promise.</param>
334 324 /// <returns>New promise.</returns>
335 public IPromise<T> Error(ErrorHandler<T> handler) {
325 public IPromise<T> Error(Func<Exception,T> handler) {
336 326 if (handler == null)
337 327 return this;
338 328
339 var medium = new Promise<T>(this, true);
329 var medium = new Promise<T>(this);
340 330
341 331 AddHandler(null, handler, null, medium);
342 332
@@ -352,14 +342,14 namespace Implab {
352 342 /// исключение возникшее при выполнении операции.</param>
353 343 /// <returns>Новое обещание, которое будет выполнено при выполнении исходного обещания.</returns>
354 344 /// <param name = "cancel"></param>
355 public IPromise<TNew> Then<TNew>(ResultMapper<T, TNew> mapper, ErrorHandler<TNew> error, Action cancel) {
345 public IPromise<TNew> Then<TNew>(Func<T, TNew> mapper, Func<Exception,TNew> error, Action cancel) {
356 346 Safe.ArgumentNotNull(mapper, "mapper");
357 347
358 348 // создаем прицепленное обещание
359 var medium = new Promise<TNew>(this, true);
349 var medium = new Promise<TNew>(this);
360 350
361 ResultHandler<T> resultHandler = result => medium.Resolve(mapper(result));
362 ErrorHandler<T> errorHandler;
351 Action<T> resultHandler = result => medium.Resolve(mapper(result));
352 Func<Exception,T> errorHandler;
363 353 if (error != null)
364 354 errorHandler = e => {
365 355 try {
@@ -396,11 +386,11 namespace Implab {
396 386 return medium;
397 387 }
398 388
399 public IPromise<TNew> Then<TNew>(ResultMapper<T, TNew> mapper, ErrorHandler<TNew> error) {
389 public IPromise<TNew> Then<TNew>(Func<T, TNew> mapper, Func<Exception,TNew> error) {
400 390 return Then(mapper, error, null);
401 391 }
402 392
403 public IPromise<TNew> Then<TNew>(ResultMapper<T, TNew> mapper) {
393 public IPromise<TNew> Then<TNew>(Func<T, TNew> mapper) {
404 394 return Then(mapper, null, null);
405 395 }
406 396
@@ -415,7 +405,7 namespace Implab {
415 405 /// исключение возникшее при выполнении текуещй операции.</param>
416 406 /// <returns>Новое обещание, которое будет выполнено по окончанию указанной аснхронной операции.</returns>
417 407 /// <param name = "cancel"></param>
418 public IPromise<TNew> Chain<TNew>(ResultMapper<T, IPromise<TNew>> chained, ErrorHandler<IPromise<TNew>> error, Action cancel) {
408 public IPromise<TNew> Chain<TNew>(Func<T, IPromise<TNew>> chained, Func<Exception,IPromise<TNew>> error, Action cancel) {
419 409
420 410 Safe.ArgumentNotNull(chained, "chained");
421 411
@@ -423,9 +413,9 namespace Implab {
423 413 // создать посредника, к которому будут подвызяваться следующие обработчики.
424 414 // когда будет выполнена реальная асинхронная операция, она обратиться к посреднику, чтобы
425 415 // передать через него результаты работы.
426 var medium = new Promise<TNew>(this, true);
416 var medium = new Promise<TNew>(this);
427 417
428 ResultHandler<T> resultHandler = delegate(T result) {
418 Action<T> resultHandler = delegate(T result) {
429 419 if (medium.IsCancelled)
430 420 return;
431 421
@@ -440,13 +430,17 namespace Implab {
440 430 // notify chained operation that it's not needed anymore
441 431 // порядок вызова Then, Cancelled важен, поскольку от этого
442 432 // зависит IsExclusive
443 medium.Cancelled(() => {
433 medium.Last(
434 null,
435 null,
436 () => {
444 437 if (promise.IsExclusive)
445 438 promise.Cancel();
446 });
439 }
440 );
447 441 };
448 442
449 ErrorHandler<T> errorHandler;
443 Func<Exception,T> errorHandler;
450 444
451 445 if (error != null)
452 446 errorHandler = delegate(Exception e) {
@@ -498,16 +492,16 namespace Implab {
498 492 return medium;
499 493 }
500 494
501 public IPromise<TNew> Chain<TNew>(ResultMapper<T, IPromise<TNew>> chained, ErrorHandler<IPromise<TNew>> error) {
495 public IPromise<TNew> Chain<TNew>(Func<T, IPromise<TNew>> chained, Func<Exception,IPromise<TNew>> error) {
502 496 return Chain(chained, error, null);
503 497 }
504 498
505 public IPromise<TNew> Chain<TNew>(ResultMapper<T, IPromise<TNew>> chained) {
499 public IPromise<TNew> Chain<TNew>(Func<T, IPromise<TNew>> chained) {
506 500 return Chain(chained, null, null);
507 501 }
508 502
509 503 public IPromise<T> Cancelled(Action handler) {
510 var medium = new Promise<T>(this,true);
504 var medium = new Promise<T>(this);
511 505 AddHandler(null, null, handler, medium);
512 506 return medium;
513 507 }
@@ -585,7 +579,7 namespace Implab {
585 579 return Join(Timeout.Infinite);
586 580 }
587 581
588 void AddHandler(ResultHandler<T> success, ErrorHandler<T> error, Action cancel, Promise<T> medium) {
582 void AddHandler(Action<T> success, Func<Exception,T> error, Action cancel, Promise<T> medium) {
589 583 if (success != null || error != null)
590 584 Interlocked.Increment(ref m_childrenCount);
591 585
@@ -759,10 +753,10 namespace Implab {
759 753
760 754 #region IPromiseBase explicit implementation
761 755
762 IPromise IPromise.Then(Action success, ErrorHandler error, Action cancel) {
756 IPromise IPromise.Then(Action success, Action<Exception> error, Action cancel) {
763 757 return Then(
764 success != null ? new ResultHandler<T>(x => success()) : null,
765 error != null ? new ErrorHandler<T>(e => {
758 success != null ? new Action<T>(x => success()) : null,
759 error != null ? new Func<Exception,T>(e => {
766 760 error(e);
767 761 return default(T);
768 762 }) : null,
@@ -770,10 +764,10 namespace Implab {
770 764 );
771 765 }
772 766
773 IPromise IPromise.Then(Action success, ErrorHandler error) {
767 IPromise IPromise.Then(Action success, Action<Exception> error) {
774 768 return Then(
775 success != null ? new ResultHandler<T>(x => success()) : null,
776 error != null ? new ErrorHandler<T>(e => {
769 success != null ? new Action<T>(x => success()) : null,
770 error != null ? new Func<Exception,T>(e => {
777 771 error(e);
778 772 return default(T);
779 773 }) : null
@@ -785,16 +779,16 namespace Implab {
785 779 return Then(x => success());
786 780 }
787 781
788 IPromise IPromise.Chain(Func<IPromise> chained, ErrorHandler<IPromise> error, Action cancel) {
782 IPromise IPromise.Chain(Func<IPromise> chained, Func<Exception,IPromise> error, Action cancel) {
789 783 return ChainNoResult(chained, error, cancel);
790 784 }
791 785
792 IPromise ChainNoResult(Func<IPromise> chained, ErrorHandler<IPromise> error, Action cancel) {
786 IPromise ChainNoResult(Func<IPromise> chained, Func<Exception,IPromise> error, Action cancel) {
793 787 Safe.ArgumentNotNull(chained, "chained");
794 788
795 var medium = new Promise<object>(this, true);
789 var medium = new Promise<object>(this);
796 790
797 ResultHandler<T> resultHandler = delegate(T result) {
791 Action<T> resultHandler = delegate {
798 792 if (medium.IsCancelled)
799 793 return;
800 794
@@ -815,7 +809,7 namespace Implab {
815 809 });
816 810 };
817 811
818 ErrorHandler<T> errorHandler;
812 Func<Exception,T> errorHandler;
819 813
820 814 if (error != null)
821 815 errorHandler = delegate(Exception e) {
@@ -866,7 +860,7 namespace Implab {
866 860
867 861 return medium;
868 862 }
869 IPromise IPromise.Chain(Func<IPromise> chained, ErrorHandler<IPromise> error) {
863 IPromise IPromise.Chain(Func<IPromise> chained, Func<Exception,IPromise> error) {
870 864 return ChainNoResult(chained, error, null);
871 865 }
872 866 IPromise IPromise.Chain(Func<IPromise> chained) {
@@ -874,11 +868,11 namespace Implab {
874 868 }
875 869
876 870
877 void IPromise.Last(Action success, ErrorHandler error, Action cancel) {
871 void IPromise.Last(Action success, Action<Exception> error, Action cancel) {
878 872 Last(x => success(), error, cancel);
879 873 }
880 874
881 void IPromise.Last(Action success, ErrorHandler error) {
875 void IPromise.Last(Action success, Action<Exception> error) {
882 876 Last(x => success(), error, null);
883 877 }
884 878
@@ -886,7 +880,7 namespace Implab {
886 880 Last(x => success(), null, null);
887 881 }
888 882
889 IPromise IPromise.Error(ErrorHandler error) {
883 IPromise IPromise.Error(Action<Exception> error) {
890 884 return Error(error);
891 885 }
892 886
@@ -12,7 +12,7 namespace Implab {
12 12 if (context == null)
13 13 return that;
14 14
15 var p = new SyncContextPromise<T>(context, that, true);
15 var p = new SyncContextPromise<T>(context, that);
16 16
17 17 that.Last(
18 18 p.Resolve,
@@ -26,7 +26,7 namespace Implab {
26 26 Safe.ArgumentNotNull(that, "that");
27 27 Safe.ArgumentNotNull(context, "context");
28 28
29 var p = new SyncContextPromise<T>(context, that, true);
29 var p = new SyncContextPromise<T>(context, that);
30 30
31 31 that.Last(
32 32 p.Resolve,
@@ -36,6 +36,24 namespace Implab {
36 36 return p;
37 37 }
38 38
39 /// <summary>
40 /// Ensures the dispatched.
41 /// </summary>
42 /// <returns>The dispatched.</returns>
43 /// <param name="that">That.</param>
44 /// <param name="head">Head.</param>
45 /// <param name="cleanup">Cleanup.</param>
46 /// <typeparam name="TPromise">The 1st type parameter.</typeparam>
47 /// <typeparam name="T">The 2nd type parameter.</typeparam>
48 public static TPromise EnsureDispatched<TPromise,T>(this TPromise that, IPromise<T> head, Action<T> cleanup) where TPromise : IPromise{
49 Safe.ArgumentNotNull(that, "that");
50 Safe.ArgumentNotNull(head, "head");
51
52 that.Last(null,null,() => head.Last(cleanup));
53
54 return that;
55 }
56
39 57 public static AsyncCallback AsyncCallback<T>(this Promise<T> that, Func<IAsyncResult,T> callback) {
40 58 Safe.ArgumentNotNull(that, "that");
41 59 Safe.ArgumentNotNull(callback, "callback");
@@ -9,8 +9,8 namespace Implab {
9 9 m_context = context;
10 10 }
11 11
12 public SyncContextPromise(SynchronizationContext context, IPromise parent, bool cancellable)
13 : base(parent, cancellable) {
12 public SyncContextPromise(SynchronizationContext context, IPromise parent)
13 : base(parent) {
14 14 Safe.ArgumentNotNull(context, "context");
15 15 m_context = context;
16 16 }
General Comments 0
You need to be logged in to leave comments. Login now