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