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