annotate Implab/Promise.cs @ 27:a236cd1f0477

fixes
author cin
date Mon, 03 Mar 2014 08:59:03 +0400
parents f0bf98e4d22c
children 81708975d6f7
Ignore whitespace changes - Everywhere: Within whitespace: At end of lines:
rev   line source
2
aa367305156b small fixes
cin
parents: 1
diff changeset
1 using System;
aa367305156b small fixes
cin
parents: 1
diff changeset
2 using System.Collections.Generic;
aa367305156b small fixes
cin
parents: 1
diff changeset
3 using System.Reflection;
aa367305156b small fixes
cin
parents: 1
diff changeset
4 using System.Diagnostics;
aa367305156b small fixes
cin
parents: 1
diff changeset
5 using System.Threading;
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
6 using Implab.Parallels;
2
aa367305156b small fixes
cin
parents: 1
diff changeset
7
aa367305156b small fixes
cin
parents: 1
diff changeset
8 namespace Implab {
aa367305156b small fixes
cin
parents: 1
diff changeset
9
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
10 public delegate void ErrorHandler(Exception e);
11
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
11 public delegate T ErrorHandler<out T>(Exception e);
10
aa33d0bb8c0c implemeted new cancellable promises concept
cin
parents: 9
diff changeset
12 public delegate void ResultHandler<in T>(T result);
aa33d0bb8c0c implemeted new cancellable promises concept
cin
parents: 9
diff changeset
13 public delegate TNew ResultMapper<in TSrc, out TNew>(TSrc result);
aa33d0bb8c0c implemeted new cancellable promises concept
cin
parents: 9
diff changeset
14 public delegate Promise<TNew> ChainedOperation<in TSrc, TNew>(TSrc result);
2
aa367305156b small fixes
cin
parents: 1
diff changeset
15
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
16 /// <summary>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
17 /// Класс для асинхронного получения результатов. Так называемое "обещание".
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
18 /// </summary>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
19 /// <typeparam name="T">Тип получаемого результата</typeparam>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
20 /// <remarks>
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 /// событий выполнения обещания, тоесть завершения операции и предоставлении результатов.</para>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
24 /// <para>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
25 /// Обещение может быть как выполнено, так и выполнено с ошибкой. Для подписки на
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
26 /// данные события клиент должен использовать методы <c>Then</c>.
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
27 /// </para>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
28 /// <para>
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 /// использует методы <c>Resolve</c> либо <c>Reject</c> для оповещения клиетна о
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 /// режиме и клиент будет оповещен в любом случае. Иначе, обработчики добавляются в
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
37 /// список в порядке подписания и в этом же порядке они будут вызваны при выполнении
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
38 /// обещания.
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
39 /// </para>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
40 /// <para>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
41 /// Обрабатывая результаты обещания можно преобразовывать результаты либо инициировать
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
42 /// связанные асинхронные операции, которые также возвращают обещания. Для этого следует
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
43 /// использовать соответствующую форму методе <c>Then</c>.
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
44 /// </para>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
45 /// <para>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
46 /// Также хорошим правилом является то, что <c>Resolve</c> и <c>Reject</c> должен вызывать
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
47 /// только инициатор обещания иначе могут возникнуть противоречия.
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
48 /// </para>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
49 /// </remarks>
25
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
50 public class Promise<T> : IPromise<T> {
2
aa367305156b small fixes
cin
parents: 1
diff changeset
51
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
52 struct HandlerDescriptor {
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
53 public ResultHandler<T> resultHandler;
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
54 public ErrorHandler errorHandler;
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
55 public Action cancellHandler;
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
56
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
57 public void Resolve(T result) {
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
58 if (resultHandler != null)
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
59 try {
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
60 resultHandler(result);
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
61 } catch (Exception e) {
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
62 Reject(e);
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
63 }
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
64 }
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
65
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
66 public void Reject(Exception err) {
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
67 if (errorHandler != null)
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
68 try {
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
69 errorHandler(err);
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
70 } catch {
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
71 }
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
72 }
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
73
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
74 public void Cancel() {
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
75 if (cancellHandler != null)
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
76 try {
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
77 cancellHandler();
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
78 } catch {
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
79 }
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
80 }
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
81 }
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
82
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
83 const int UnresolvedSate = 0;
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
84 const int TransitionalState = 1;
25
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
85 const int SucceededState = 2;
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
86 const int RejectedState = 3;
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
87 const int CancelledState = 4;
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
88
25
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
89 readonly IPromiseBase m_parent;
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
90 readonly bool m_cancellable;
9
cin
parents: 7
diff changeset
91
10
aa33d0bb8c0c implemeted new cancellable promises concept
cin
parents: 9
diff changeset
92 int m_childrenCount = 0;
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
93 int m_state;
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
94 T m_result;
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
95 Exception m_error;
9
cin
parents: 7
diff changeset
96
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
97 readonly MTQueue<HandlerDescriptor> m_handlers = new MTQueue<HandlerDescriptor>();
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
98
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
99 public Promise() {
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
100 m_cancellable = true;
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
101 }
2
aa367305156b small fixes
cin
parents: 1
diff changeset
102
25
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
103 public Promise(IPromiseBase parent, bool cancellable) {
7
7ea9363fef6c inital progress handling
cin
parents: 6
diff changeset
104 m_cancellable = cancellable;
7ea9363fef6c inital progress handling
cin
parents: 6
diff changeset
105 m_parent = parent;
7ea9363fef6c inital progress handling
cin
parents: 6
diff changeset
106 }
7ea9363fef6c inital progress handling
cin
parents: 6
diff changeset
107
10
aa33d0bb8c0c implemeted new cancellable promises concept
cin
parents: 9
diff changeset
108 void InternalCancel() {
aa33d0bb8c0c implemeted new cancellable promises concept
cin
parents: 9
diff changeset
109 // don't try to cancel parent :)
aa33d0bb8c0c implemeted new cancellable promises concept
cin
parents: 9
diff changeset
110 Cancel(false);
aa33d0bb8c0c implemeted new cancellable promises concept
cin
parents: 9
diff changeset
111 }
2
aa367305156b small fixes
cin
parents: 1
diff changeset
112
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
113 bool BeginTransit() {
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
114 return UnresolvedSate == Interlocked.CompareExchange(ref m_state, TransitionalState, UnresolvedSate);
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
115 }
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
116
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
117 void CompleteTransit(int state) {
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
118 if (TransitionalState != Interlocked.CompareExchange(ref m_state, state, TransitionalState))
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
119 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
120 }
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
121
25
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
122 void WaitTransition() {
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
123 while (m_state == TransitionalState) {
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
124 /* noop */
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
125 }
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
126 }
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
127
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
128 public bool IsResolved {
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
129 get {
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
130 return m_state > 1;
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
131 }
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
132 }
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
133
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
134 public bool IsCancelled {
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
135 get {
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
136 return m_state == CancelledState;
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
137 }
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
138 }
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
139
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
140 /// <summary>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
141 /// Выполняет обещание, сообщая об успешном выполнении.
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
142 /// </summary>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
143 /// <param name="result">Результат выполнения.</param>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
144 /// <exception cref="InvalidOperationException">Данное обещание уже выполнено</exception>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
145 public void Resolve(T result) {
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
146 if (BeginTransit()) {
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
147 m_result = result;
25
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
148 CompleteTransit(SucceededState);
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
149 OnStateChanged();
25
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
150 } else {
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
151 WaitTransition();
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
152 if (m_state != CancelledState)
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
153 throw new InvalidOperationException("The promise is already resolved");
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
154 }
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
155 }
2
aa367305156b small fixes
cin
parents: 1
diff changeset
156
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
157 /// <summary>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
158 /// Выполняет обещание, сообщая об ошибке
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
159 /// </summary>
16
cin
parents: 15
diff changeset
160 /// <remarks>
cin
parents: 15
diff changeset
161 /// Поскольку обещание должно работать в многопточной среде, при его выполнении сразу несколько потоков
cin
parents: 15
diff changeset
162 /// могу вернуть ошибку, при этом только первая будет использована в качестве результата, остальные
cin
parents: 15
diff changeset
163 /// будут проигнорированы.
cin
parents: 15
diff changeset
164 /// </remarks>
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
165 /// <param name="error">Исключение возникшее при выполнении операции</param>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
166 /// <exception cref="InvalidOperationException">Данное обещание уже выполнено</exception>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
167 public void Reject(Exception error) {
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
168 if (BeginTransit()) {
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
169 m_error = error;
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
170 CompleteTransit(RejectedState);
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
171 OnStateChanged();
25
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
172 } else {
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
173 WaitTransition();
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
174 if (m_state == SucceededState)
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
175 throw new InvalidOperationException("The promise is already resolved");
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
176 }
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
177 }
2
aa367305156b small fixes
cin
parents: 1
diff changeset
178
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
179 /// <summary>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
180 /// Отменяет операцию, если это возможно.
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
181 /// </summary>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
182 /// <returns><c>true</c> Операция была отменена, обработчики не будут вызваны.<c>false</c> отмена не возможна, поскольку обещание уже выполнено и обработчики отработали.</returns>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
183 public bool Cancel() {
9
cin
parents: 7
diff changeset
184 return Cancel(true);
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
185 }
2
aa367305156b small fixes
cin
parents: 1
diff changeset
186
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
187 /// <summary>
11
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
188 /// Adds new handlers to this promise.
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
189 /// </summary>
11
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
190 /// <param name="success">The handler of the successfully completed operation.
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
191 /// This handler will recieve an operation result as a parameter.</param>
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
192 /// <param name="error">Handles an exception that may occur during the operation.</param>
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
193 /// <returns>The new promise chained to this one.</returns>
26
f0bf98e4d22c refactoring
cin
parents: 25
diff changeset
194 public IPromise<T> Then(ResultHandler<T> success, ErrorHandler error) {
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
195 if (success == null && error == null)
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
196 return this;
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
197
11
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
198 var medium = new Promise<T>(this, true);
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
199
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
200 ResultHandler<T> resultHandler;
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
201 if (success != null)
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
202 resultHandler = x => {
10
aa33d0bb8c0c implemeted new cancellable promises concept
cin
parents: 9
diff changeset
203 success(x);
aa33d0bb8c0c implemeted new cancellable promises concept
cin
parents: 9
diff changeset
204 medium.Resolve(x);
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
205 };
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
206 else
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
207 resultHandler = medium.Resolve;
2
aa367305156b small fixes
cin
parents: 1
diff changeset
208
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
209 ErrorHandler errorHandler;
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
210 if (error != null)
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
211 errorHandler = x => {
25
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
212 // несмотря на то, что обработчик ошибки вызывается безопасно,
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
213 // т.е. возникшие в нем ошибки будут подавлены, нам нужно
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
214 // гарантировать, что ошибка будет передана дальше по цепочке обещаний
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
215 try {
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
216 error(x);
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
217 } catch { }
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
218 medium.Reject(x);
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
219 };
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
220 else
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
221 errorHandler = medium.Reject;
2
aa367305156b small fixes
cin
parents: 1
diff changeset
222
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
223 AddHandler(resultHandler, errorHandler, medium.InternalCancel);
2
aa367305156b small fixes
cin
parents: 1
diff changeset
224
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
225 return medium;
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
226 }
2
aa367305156b small fixes
cin
parents: 1
diff changeset
227
26
f0bf98e4d22c refactoring
cin
parents: 25
diff changeset
228 public IPromiseBase Then(Action success,ErrorHandler error)
f0bf98e4d22c refactoring
cin
parents: 25
diff changeset
229 {
f0bf98e4d22c refactoring
cin
parents: 25
diff changeset
230 return Then(x => success(), error);
f0bf98e4d22c refactoring
cin
parents: 25
diff changeset
231 }
f0bf98e4d22c refactoring
cin
parents: 25
diff changeset
232
f0bf98e4d22c refactoring
cin
parents: 25
diff changeset
233 public IPromiseBase Then(Action success)
f0bf98e4d22c refactoring
cin
parents: 25
diff changeset
234 {
f0bf98e4d22c refactoring
cin
parents: 25
diff changeset
235 return Then(success);
f0bf98e4d22c refactoring
cin
parents: 25
diff changeset
236 }
f0bf98e4d22c refactoring
cin
parents: 25
diff changeset
237
11
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
238 /// <summary>
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
239 /// Adds new handlers to this promise.
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
240 /// </summary>
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
241 /// <param name="success">The handler of the successfully completed operation.
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
242 /// This handler will recieve an operation result as a parameter.</param>
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
243 /// <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>
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
244 /// <returns>The new promise chained to this one.</returns>
26
f0bf98e4d22c refactoring
cin
parents: 25
diff changeset
245 public IPromise<T> Then(ResultHandler<T> success, ErrorHandler<T> error) {
11
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
246 if (success == null && error == null)
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
247 return this;
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
248
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
249 var medium = new Promise<T>(this, true);
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
250
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
251 ResultHandler<T> resultHandler;
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
252 ErrorHandler errorHandler;
11
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
253
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
254 if (success != null)
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
255 resultHandler = x => {
11
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
256 success(x);
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
257 medium.Resolve(x);
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
258 };
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
259 else
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
260 resultHandler = medium.Resolve;
11
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
261
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
262 if (error != null)
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
263 errorHandler = x => {
11
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
264 try {
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
265 medium.Resolve(error(x));
25
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
266 } catch(Exception e) {
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
267 medium.Reject(e);
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
268 }
11
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
269 };
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
270 else
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
271 errorHandler = medium.Reject;
11
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
272
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
273 AddHandler(resultHandler, errorHandler, medium.InternalCancel);
11
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
274
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
275 return medium;
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
276 }
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
277
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
278
26
f0bf98e4d22c refactoring
cin
parents: 25
diff changeset
279 public IPromise<T> Then(ResultHandler<T> success) {
11
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
280 if (success == null)
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
281 return this;
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
282
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
283 var medium = new Promise<T>(this, true);
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
284
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
285 ResultHandler<T> resultHandler;
25
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
286
11
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
287 if (success != null)
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
288 resultHandler = x => {
11
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
289 success(x);
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
290 medium.Resolve(x);
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
291 };
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
292 else
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
293 resultHandler = medium.Resolve;
11
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
294
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
295 AddHandler(resultHandler, medium.Reject, medium.InternalCancel);
11
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
296
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
297 return medium;
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
298 }
2
aa367305156b small fixes
cin
parents: 1
diff changeset
299
26
f0bf98e4d22c refactoring
cin
parents: 25
diff changeset
300 public IPromise<T> Error(ErrorHandler error) {
f0bf98e4d22c refactoring
cin
parents: 25
diff changeset
301 return Then((ResultHandler<T>)null, error);
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
302 }
2
aa367305156b small fixes
cin
parents: 1
diff changeset
303
11
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
304 /// <summary>
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
305 /// Handles error and allows to keep the promise.
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
306 /// </summary>
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
307 /// <remarks>
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
308 /// If the specified handler throws an exception, this exception will be used to reject the promise.
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
309 /// </remarks>
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
310 /// <param name="handler">The error handler which returns the result of the promise.</param>
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
311 /// <returns>New promise.</returns>
26
f0bf98e4d22c refactoring
cin
parents: 25
diff changeset
312 public IPromise<T> Error(ErrorHandler<T> handler) {
11
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
313 if (handler == null)
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
314 return this;
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
315
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
316 var medium = new Promise<T>(this, true);
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
317
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
318 AddHandler(
27
cin
parents: 26
diff changeset
319 x => medium.Resolve(x),
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
320 e => {
11
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
321 try {
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
322 medium.Resolve(handler(e));
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
323 } catch (Exception e2) {
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
324 medium.Reject(e2);
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
325 }
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
326 },
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
327 medium.InternalCancel
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
328 );
11
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
329
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
330 return medium;
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
331 }
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
332
26
f0bf98e4d22c refactoring
cin
parents: 25
diff changeset
333 public IPromise<T> Anyway(Action handler) {
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
334 if (handler == null)
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
335 return this;
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
336
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
337 var medium = new Promise<T>();
2
aa367305156b small fixes
cin
parents: 1
diff changeset
338
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
339 AddHandler(
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
340 x => {
10
aa33d0bb8c0c implemeted new cancellable promises concept
cin
parents: 9
diff changeset
341 // to avoid handler being called multiple times we handle exception by ourselfs
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
342 try {
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
343 handler();
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
344 medium.Resolve(x);
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
345 } catch (Exception e) {
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
346 medium.Reject(e);
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
347 }
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
348 },
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
349
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
350 e => {
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
351 try {
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
352 handler();
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
353 } catch { }
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
354 medium.Reject(e);
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
355 },
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
356
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
357 medium.InternalCancel
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
358 );
2
aa367305156b small fixes
cin
parents: 1
diff changeset
359
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
360 return medium;
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
361 }
2
aa367305156b small fixes
cin
parents: 1
diff changeset
362
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
363 /// <summary>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
364 /// Позволяет преобразовать результат выполения операции к новому типу.
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
365 /// </summary>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
366 /// <typeparam name="TNew">Новый тип результата.</typeparam>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
367 /// <param name="mapper">Преобразование результата к новому типу.</param>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
368 /// <param name="error">Обработчик ошибки. Данный обработчик получит
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
369 /// исключение возникшее при выполнении операции.</param>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
370 /// <returns>Новое обещание, которое будет выполнено при выполнении исходного обещания.</returns>
26
f0bf98e4d22c refactoring
cin
parents: 25
diff changeset
371 public IPromise<TNew> Map<TNew>(ResultMapper<T, TNew> mapper, ErrorHandler error) {
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
372 if (mapper == null)
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
373 throw new ArgumentNullException("mapper");
2
aa367305156b small fixes
cin
parents: 1
diff changeset
374
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
375 // создаем прицепленное обещание
10
aa33d0bb8c0c implemeted new cancellable promises concept
cin
parents: 9
diff changeset
376 var chained = new Promise<TNew>();
2
aa367305156b small fixes
cin
parents: 1
diff changeset
377
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
378 ResultHandler<T> resultHandler = result => chained.Resolve(mapper(result));
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
379 ErrorHandler errorHandler = delegate(Exception e) {
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
380 if (error != null)
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
381 try {
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
382 error(e);
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
383 } catch { }
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
384 // в случае ошибки нужно передать исключение дальше по цепочке
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
385 chained.Reject(e);
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
386 };
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
387
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
388
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
389 AddHandler(
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
390 resultHandler,
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
391 errorHandler,
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
392 chained.InternalCancel
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
393 );
2
aa367305156b small fixes
cin
parents: 1
diff changeset
394
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
395 return chained;
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
396 }
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
397
26
f0bf98e4d22c refactoring
cin
parents: 25
diff changeset
398 public IPromise<TNew> Map<TNew>(ResultMapper<T, TNew> mapper) {
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
399 return Map(mapper, null);
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
400 }
2
aa367305156b small fixes
cin
parents: 1
diff changeset
401
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
402 /// <summary>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
403 /// Сцепляет несколько аснхронных операций. Указанная асинхронная операция будет вызвана после
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
404 /// выполнения текущей, а результат текущей операции может быть использован для инициализации
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 /// </summary>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
407 /// <typeparam name="TNew">Тип результата указанной асинхронной операции.</typeparam>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
408 /// <param name="chained">Асинхронная операция, которая должна будет начаться после выполнения текущей.</param>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
409 /// <param name="error">Обработчик ошибки. Данный обработчик получит
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
410 /// исключение возникшее при выполнении текуещй операции.</param>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
411 /// <returns>Новое обещание, которое будет выполнено по окончанию указанной аснхронной операции.</returns>
26
f0bf98e4d22c refactoring
cin
parents: 25
diff changeset
412 public IPromise<TNew> Chain<TNew>(ChainedOperation<T, TNew> chained, ErrorHandler error) {
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
413
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
414 // проблема в том, что на момент связывания еще не начата асинхронная операция, поэтому нужно
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
415 // создать посредника, к которому будут подвызяваться следующие обработчики.
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
416 // когда будет выполнена реальная асинхронная операция, она обратиться к посреднику, чтобы
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
417 // передать через него результаты работы.
10
aa33d0bb8c0c implemeted new cancellable promises concept
cin
parents: 9
diff changeset
418 var medium = new Promise<TNew>(this, true);
2
aa367305156b small fixes
cin
parents: 1
diff changeset
419
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
420 ResultHandler<T> resultHandler = delegate(T result) {
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
421 if (medium.IsCancelled)
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
422 return;
10
aa33d0bb8c0c implemeted new cancellable promises concept
cin
parents: 9
diff changeset
423
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
424 var promise = chained(result);
10
aa33d0bb8c0c implemeted new cancellable promises concept
cin
parents: 9
diff changeset
425
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
426 // notify chained operation that it's not needed
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
427 medium.Cancelled(() => promise.Cancel());
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
428 promise.Then(
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
429 x => medium.Resolve(x),
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
430 e => medium.Reject(e)
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
431 );
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
432 };
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
433
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
434 ErrorHandler errorHandler = delegate(Exception e) {
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
435 if (error != null)
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
436 error(e);
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
437 // в случае ошибки нужно передать исключение дальше по цепочке
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
438 medium.Reject(e);
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
439 };
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
440
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
441 AddHandler(
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
442 resultHandler,
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
443 errorHandler,
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
444 medium.InternalCancel
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
445 );
2
aa367305156b small fixes
cin
parents: 1
diff changeset
446
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
447 return medium;
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
448 }
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
449
26
f0bf98e4d22c refactoring
cin
parents: 25
diff changeset
450 public IPromise<TNew> Chain<TNew>(ChainedOperation<T, TNew> chained) {
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
451 return Chain(chained, null);
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
452 }
2
aa367305156b small fixes
cin
parents: 1
diff changeset
453
26
f0bf98e4d22c refactoring
cin
parents: 25
diff changeset
454 public IPromise<T> Cancelled(Action handler) {
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
455 AddHandler(null, null, handler);
10
aa33d0bb8c0c implemeted new cancellable promises concept
cin
parents: 9
diff changeset
456 return this;
aa33d0bb8c0c implemeted new cancellable promises concept
cin
parents: 9
diff changeset
457 }
aa33d0bb8c0c implemeted new cancellable promises concept
cin
parents: 9
diff changeset
458
25
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
459 /// <summary>
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
460 /// Adds the specified handler for all cases (success, error, cancel)
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
461 /// </summary>
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
462 /// <param name="handler">The handler that will be called anyway</param>
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
463 /// <returns>self</returns>
26
f0bf98e4d22c refactoring
cin
parents: 25
diff changeset
464 public IPromise<T> Finally(Action handler) {
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
465 if (handler == null)
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
466 throw new ArgumentNullException("handler");
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
467 AddHandler(
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
468 x => handler(),
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
469 e => handler(),
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
470 handler
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
471 );
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
472 return this;
10
aa33d0bb8c0c implemeted new cancellable promises concept
cin
parents: 9
diff changeset
473 }
aa33d0bb8c0c implemeted new cancellable promises concept
cin
parents: 9
diff changeset
474
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
475 /// <summary>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
476 /// Дожидается отложенного обещания и в случае успеха, возвращает
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
477 /// его, результат, в противном случае бросает исключение.
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
478 /// </summary>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
479 /// <remarks>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
480 /// <para>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
481 /// Если ожидание обещания было прервано по таймауту, это не значит,
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
482 /// что обещание было отменено или что-то в этом роде, это только
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
483 /// означает, что мы его не дождались, однако все зарегистрированные
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
484 /// обработчики, как были так остались и они будут вызваны, когда
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
485 /// обещание будет выполнено.
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
486 /// </para>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
487 /// <para>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
488 /// Такое поведение вполне оправдано поскольку таймаут может истечь
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
489 /// в тот момент, когда началась обработка цепочки обработчиков, и
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
490 /// к тому же текущее обещание может стоять в цепочке обещаний и его
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
491 /// отклонение может привести к непрогнозируемому результату.
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
492 /// </para>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
493 /// </remarks>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
494 /// <param name="timeout">Время ожидания</param>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
495 /// <returns>Результат выполнения обещания</returns>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
496 public T Join(int timeout) {
10
aa33d0bb8c0c implemeted new cancellable promises concept
cin
parents: 9
diff changeset
497 var evt = new ManualResetEvent(false);
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
498 Anyway(() => evt.Set());
10
aa33d0bb8c0c implemeted new cancellable promises concept
cin
parents: 9
diff changeset
499 Cancelled(() => evt.Set());
2
aa367305156b small fixes
cin
parents: 1
diff changeset
500
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
501 if (!evt.WaitOne(timeout, true))
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
502 throw new TimeoutException();
2
aa367305156b small fixes
cin
parents: 1
diff changeset
503
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
504 switch (m_state) {
25
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
505 case SucceededState:
10
aa33d0bb8c0c implemeted new cancellable promises concept
cin
parents: 9
diff changeset
506 return m_result;
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
507 case CancelledState:
10
aa33d0bb8c0c implemeted new cancellable promises concept
cin
parents: 9
diff changeset
508 throw new OperationCanceledException();
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
509 case RejectedState:
10
aa33d0bb8c0c implemeted new cancellable promises concept
cin
parents: 9
diff changeset
510 throw new TargetInvocationException(m_error);
aa33d0bb8c0c implemeted new cancellable promises concept
cin
parents: 9
diff changeset
511 default:
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
512 throw new ApplicationException(String.Format("Invalid promise state {0}", m_state));
10
aa33d0bb8c0c implemeted new cancellable promises concept
cin
parents: 9
diff changeset
513 }
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
514 }
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
515
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
516 public T Join() {
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
517 return Join(Timeout.Infinite);
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
518 }
2
aa367305156b small fixes
cin
parents: 1
diff changeset
519
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
520 void AddHandler(ResultHandler<T> success, ErrorHandler error, Action cancel) {
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
521 Interlocked.Increment(ref m_childrenCount);
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
522
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
523 HandlerDescriptor handler = new HandlerDescriptor {
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
524 resultHandler = success,
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
525 errorHandler = error,
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
526 cancellHandler = cancel
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
527 };
2
aa367305156b small fixes
cin
parents: 1
diff changeset
528
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
529 bool queued;
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
530
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
531 if (!IsResolved) {
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
532 m_handlers.Enqueue(handler);
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
533 queued = true;
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
534 } else {
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
535 // 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
536 queued = false;
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
537 InvokeHandler(handler);
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
538 }
2
aa367305156b small fixes
cin
parents: 1
diff changeset
539
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
540 if (queued && IsResolved && m_handlers.TryDequeue(out handler))
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
541 // 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
542 // 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
543 // therefore we will fetch a handler from the queue and execute it
27
cin
parents: 26
diff changeset
544 // note that fetched handler may be not the one that we have added
cin
parents: 26
diff changeset
545 // even we can fetch no handlers at all :)
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
546 InvokeHandler(handler);
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
547 }
2
aa367305156b small fixes
cin
parents: 1
diff changeset
548
27
cin
parents: 26
diff changeset
549 protected virtual void InvokeHandler(HandlerDescriptor handler) {
10
aa33d0bb8c0c implemeted new cancellable promises concept
cin
parents: 9
diff changeset
550 switch (m_state) {
25
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
551 case SucceededState:
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
552 handler.Resolve(m_result);
10
aa33d0bb8c0c implemeted new cancellable promises concept
cin
parents: 9
diff changeset
553 break;
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
554 case RejectedState:
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
555 handler.Reject(m_error);
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
556 break;
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
557 case CancelledState:
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
558 handler.Cancel();
10
aa33d0bb8c0c implemeted new cancellable promises concept
cin
parents: 9
diff changeset
559 break;
aa33d0bb8c0c implemeted new cancellable promises concept
cin
parents: 9
diff changeset
560 default:
aa33d0bb8c0c implemeted new cancellable promises concept
cin
parents: 9
diff changeset
561 // do nothing
aa33d0bb8c0c implemeted new cancellable promises concept
cin
parents: 9
diff changeset
562 return;
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
563 }
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
564 }
2
aa367305156b small fixes
cin
parents: 1
diff changeset
565
11
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
566 protected virtual void OnStateChanged() {
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
567 HandlerDescriptor handler;
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
568 while (m_handlers.TryDequeue(out handler))
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
569 InvokeHandler(handler);
11
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
570 }
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
571
9
cin
parents: 7
diff changeset
572 public bool IsExclusive {
cin
parents: 7
diff changeset
573 get {
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
574 return m_childrenCount <= 1;
9
cin
parents: 7
diff changeset
575 }
cin
parents: 7
diff changeset
576 }
cin
parents: 7
diff changeset
577
11
6ec82bf68c8e refactoring
cin
parents: 10
diff changeset
578 protected bool Cancel(bool dependencies) {
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
579 if (BeginTransit()) {
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
580 CompleteTransit(CancelledState);
10
aa33d0bb8c0c implemeted new cancellable promises concept
cin
parents: 9
diff changeset
581 OnStateChanged();
9
cin
parents: 7
diff changeset
582
19
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
583 if (dependencies && m_parent != null && m_parent.IsExclusive)
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
584 m_parent.Cancel();
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
585
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
586 return true;
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
587 } else {
e3935fdf59a2 Promise is rewritten to use interlocked operations instead of locks
cin
parents: 16
diff changeset
588 return false;
9
cin
parents: 7
diff changeset
589 }
cin
parents: 7
diff changeset
590 }
15
0f982f9b7d4d implemented parallel map and foreach for arrays
cin
parents: 14
diff changeset
591
25
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
592 /// <summary>
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
593 /// Объединяет несколько обещаний в одно, результатом которого является массив результатов других обещаний.
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
594 /// Если хотябы одно из переданных обещаний не будет выполнено, то новое обещение тоже не будет выполнено.
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
595 /// При отмене нового обещания, переданные обещания также будут отменены, если никто больше на них не подписан.
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
596 /// </summary>
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
597 /// <param name="promises">Список обещаний. Если список пустой, то результирующее обещание возвращается уже выполненным.</param>
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
598 /// <returns>Обещание объединяющее в себе результат переданных обещаний.</returns>
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
599 /// <exception cref="ArgumentNullException"><paramref name="promises"/> не может быть null</exception>
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
600 public static Promise<T[]> CreateComposite(IList<Promise<T>> promises) {
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
601 if (promises == null)
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
602 throw new ArgumentNullException();
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
603
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
604 // создаем аккумулятор для результатов и результирующее обещание
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
605 var result = new T[promises.Count];
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
606 var promise = new Promise<T[]>();
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
607
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
608 // special case
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
609 if (promises.Count == 0) {
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
610 promise.Resolve(result);
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
611 return promise;
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
612 }
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
613
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
614 int pending = promises.Count;
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
615
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
616 for (int i = 0; i < promises.Count; i++) {
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
617 var dest = i;
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
618
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
619 promises[i].Then(
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
620 x => {
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
621 result[dest] = x;
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
622 if(Interlocked.Decrement(ref pending) == 0)
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
623 promise.Resolve(result);
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
624 },
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
625 e => promise.Reject(e)
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
626 );
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
627 }
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
628
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
629 promise.Cancelled(
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
630 () => {
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
631 foreach(var d in promises)
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
632 if(d.IsExclusive)
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
633 d.Cancel();
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
634 }
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
635 );
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
636
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
637 return promise;
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
638 }
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
639
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
640 public static Promise<T> ResultToPromise(T result) {
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
641 var p = new Promise<T>();
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
642 p.Resolve(result);
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
643 return p;
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
644 }
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
645
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
646 public static Promise<T> ExceptionToPromise(Exception error) {
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
647 if (error == null)
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
648 throw new ArgumentNullException();
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
649
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
650 var p = new Promise<T>();
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
651 p.Reject(error);
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
652 return p;
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
653 }
9bf5b23650c9 refactoring
cin
parents: 19
diff changeset
654
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
655 }
2
aa367305156b small fixes
cin
parents: 1
diff changeset
656 }