Mercurial > pub > ImplabNet
annotate Implab/Promise.cs @ 94:a43745f81f10 v2
minor fixes
author | cin |
---|---|
date | Thu, 23 Oct 2014 17:50:09 +0400 |
parents | 4f20870d0816 |
children | daffa72a1cec |
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); | |
76 } catch (TransientPromiseException err2) { | |
77 if (medium != null) | |
78 medium.Reject(err2.InnerException); | |
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()) { |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
206 m_error = 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> |
76 | 354 public IPromise<TNew> Then<TNew>(ResultMapper<T, TNew> mapper, ErrorHandler<TNew> error, Action cancel) { |
355 Safe.ArgumentNotNull(mapper, "mapper"); | |
356 | |
357 // создаем прицепленное обещание | |
358 var medium = new Promise<TNew>(this, true); | |
2 | 359 |
76 | 360 ResultHandler<T> resultHandler = result => medium.Resolve(mapper(result)); |
72 | 361 ErrorHandler<T> errorHandler; |
362 if (error != null) | |
363 errorHandler = e => { | |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
364 try { |
76 | 365 medium.Resolve(error(e)); |
72 | 366 } catch (Exception e2) { |
367 // в случае ошибки нужно передать исключение дальше по цепочке | |
76 | 368 medium.Reject(e2); |
72 | 369 } |
370 return default(T); | |
371 }; | |
372 else | |
373 errorHandler = e => { | |
76 | 374 medium.Reject(e); |
72 | 375 return default(T); |
376 }; | |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
377 |
76 | 378 Action cancelHandler; |
379 if (cancel != null) | |
380 cancelHandler = () => { | |
381 cancel(); | |
382 medium.Cancel(); | |
383 }; | |
384 else | |
385 cancelHandler = medium.Cancel; | |
386 | |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
387 |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
388 AddHandler( |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
389 resultHandler, |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
390 errorHandler, |
76 | 391 cancelHandler, |
72 | 392 null |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
393 ); |
2 | 394 |
76 | 395 return medium; |
396 } | |
397 | |
398 public IPromise<TNew> Then<TNew>(ResultMapper<T, TNew> mapper, ErrorHandler<TNew> error) { | |
399 return Then(mapper, error, null); | |
6
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 |
75 | 402 public IPromise<TNew> Then<TNew>(ResultMapper<T, TNew> mapper) { |
76 | 403 return Then(mapper, null, null); |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
404 } |
2 | 405 |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
406 /// <summary> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
407 /// Сцепляет несколько аснхронных операций. Указанная асинхронная операция будет вызвана после |
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 /// </summary> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
411 /// <typeparam name="TNew">Тип результата указанной асинхронной операции.</typeparam> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
412 /// <param name="chained">Асинхронная операция, которая должна будет начаться после выполнения текущей.</param> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
413 /// <param name="error">Обработчик ошибки. Данный обработчик получит |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
414 /// исключение возникшее при выполнении текуещй операции.</param> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
415 /// <returns>Новое обещание, которое будет выполнено по окончанию указанной аснхронной операции.</returns> |
76 | 416 public IPromise<TNew> Chain<TNew>(ResultMapper<T, IPromise<TNew>> chained, ErrorHandler<IPromise<TNew>> error, Action cancel) { |
417 | |
418 Safe.ArgumentNotNull(chained, "chained"); | |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
419 |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
420 // проблема в том, что на момент связывания еще не начата асинхронная операция, поэтому нужно |
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 // передать через него результаты работы. |
10 | 424 var medium = new Promise<TNew>(this, true); |
2 | 425 |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
426 ResultHandler<T> resultHandler = delegate(T result) { |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
427 if (medium.IsCancelled) |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
428 return; |
10 | 429 |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
430 var promise = chained(result); |
10 | 431 |
76 | 432 promise.Last( |
72 | 433 medium.Resolve, |
76 | 434 medium.Reject, |
435 () => medium.Reject(new OperationCanceledException()) // внешняя отмена связанной операции рассматривается как ошибка | |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
436 ); |
33
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
437 |
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
438 // 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
|
439 // порядок вызова Then, Cancelled важен, поскольку от этого |
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
440 // зависит IsExclusive |
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
441 medium.Cancelled(() => { |
72 | 442 if (promise.IsExclusive) |
33
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
443 promise.Cancel(); |
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
444 }); |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
445 }; |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
446 |
76 | 447 ErrorHandler<T> errorHandler; |
448 | |
449 if (error != null) | |
450 errorHandler = delegate(Exception e) { | |
72 | 451 try { |
76 | 452 var promise = error(e); |
453 | |
454 promise.Last( | |
455 medium.Resolve, | |
456 medium.Reject, | |
457 () => medium.Reject(new OperationCanceledException()) // внешняя отмена связанной операции рассматривается как ошибка | |
458 ); | |
459 | |
460 // notify chained operation that it's not needed anymore | |
461 // порядок вызова Then, Cancelled важен, поскольку от этого | |
462 // зависит IsExclusive | |
463 medium.Cancelled(() => { | |
464 if (promise.IsExclusive) | |
465 promise.Cancel(); | |
466 }); | |
72 | 467 } catch (Exception e2) { |
468 medium.Reject(e2); | |
469 } | |
76 | 470 return default(T); |
471 }; | |
472 else | |
473 errorHandler = err => { | |
474 medium.Reject(err); | |
475 return default(T); | |
476 }; | |
477 | |
478 | |
479 Action cancelHandler; | |
480 if (cancel != null) | |
481 cancelHandler = () => { | |
482 if (cancel != null) | |
483 cancel(); | |
484 medium.Cancel(); | |
485 }; | |
486 else | |
487 cancelHandler = medium.Cancel; | |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
488 |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
489 AddHandler( |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
490 resultHandler, |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
491 errorHandler, |
76 | 492 cancelHandler, |
72 | 493 null |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
494 ); |
2 | 495 |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
496 return medium; |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
497 } |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
498 |
76 | 499 public IPromise<TNew> Chain<TNew>(ResultMapper<T, IPromise<TNew>> chained, ErrorHandler<IPromise<TNew>> error) { |
500 return Chain(chained, error, null); | |
501 } | |
502 | |
503 public IPromise<TNew> Chain<TNew>(ResultMapper<T, IPromise<TNew>> chained) { | |
504 return Chain(chained, null, null); | |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
505 } |
2 | 506 |
26 | 507 public IPromise<T> Cancelled(Action handler) { |
76 | 508 var medium = new Promise<T>(this,true); |
74 | 509 AddHandler(null, null, handler, medium); |
510 return medium; | |
10 | 511 } |
512 | |
25 | 513 /// <summary> |
514 /// Adds the specified handler for all cases (success, error, cancel) | |
515 /// </summary> | |
516 /// <param name="handler">The handler that will be called anyway</param> | |
517 /// <returns>self</returns> | |
76 | 518 public IPromise<T> Anyway(Action handler) { |
519 Safe.ArgumentNotNull(handler, "handler"); | |
520 | |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
521 AddHandler( |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
522 x => handler(), |
72 | 523 e => { |
524 handler(); | |
525 throw new TransientPromiseException(e); | |
526 }, | |
527 handler, | |
528 null | |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
529 ); |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
530 return this; |
10 | 531 } |
532 | |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
533 /// <summary> |
29 | 534 /// Преобразует результат обещания к нужному типу |
535 /// </summary> | |
536 /// <typeparam name="T2"></typeparam> | |
537 /// <returns></returns> | |
538 public IPromise<T2> Cast<T2>() { | |
75 | 539 return Then(x => (T2)(object)x, null); |
29 | 540 } |
541 | |
542 /// <summary> | |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
543 /// Дожидается отложенного обещания и в случае успеха, возвращает |
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 /// </summary> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
546 /// <remarks> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
547 /// <para> |
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 /// что обещание было отменено или что-то в этом роде, это только |
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 /// </para> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
554 /// <para> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
555 /// Такое поведение вполне оправдано поскольку таймаут может истечь |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
556 /// в тот момент, когда началась обработка цепочки обработчиков, и |
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 /// </para> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
560 /// </remarks> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
561 /// <param name="timeout">Время ожидания</param> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
562 /// <returns>Результат выполнения обещания</returns> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
563 public T Join(int timeout) { |
10 | 564 var evt = new ManualResetEvent(false); |
76 | 565 Anyway(() => evt.Set()); |
2 | 566 |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
567 if (!evt.WaitOne(timeout, true)) |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
568 throw new TimeoutException(); |
2 | 569 |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
570 switch (m_state) { |
71 | 571 case SUCCEEDED_STATE: |
10 | 572 return m_result; |
71 | 573 case CANCELLED_STATE: |
10 | 574 throw new OperationCanceledException(); |
71 | 575 case REJECTED_STATE: |
10 | 576 throw new TargetInvocationException(m_error); |
577 default: | |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
578 throw new ApplicationException(String.Format("Invalid promise state {0}", m_state)); |
10 | 579 } |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
580 } |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
581 |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
582 public T Join() { |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
583 return Join(Timeout.Infinite); |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
584 } |
2 | 585 |
72 | 586 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
|
587 if (success != null || error != null) |
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
588 Interlocked.Increment(ref m_childrenCount); |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
589 |
72 | 590 var handler = new HandlerDescriptor { |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
591 resultHandler = success, |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
592 errorHandler = error, |
72 | 593 cancellHandler = cancel, |
594 medium = medium | |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
595 }; |
2 | 596 |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
597 bool queued; |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
598 |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
599 if (!IsResolved) { |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
600 m_handlers.Enqueue(handler); |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
601 queued = true; |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
602 } else { |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
603 // 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
|
604 queued = false; |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
605 InvokeHandler(handler); |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
606 } |
2 | 607 |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
608 if (queued && IsResolved && m_handlers.TryDequeue(out handler)) |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
609 // 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
|
610 // 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
|
611 // therefore we will fetch a handler from the queue and execute it |
27 | 612 // note that fetched handler may be not the one that we have added |
613 // even we can fetch no handlers at all :) | |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
614 InvokeHandler(handler); |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
615 } |
2 | 616 |
27 | 617 protected virtual void InvokeHandler(HandlerDescriptor handler) { |
10 | 618 switch (m_state) { |
71 | 619 case SUCCEEDED_STATE: |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
620 handler.Resolve(m_result); |
10 | 621 break; |
71 | 622 case REJECTED_STATE: |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
623 handler.Reject(m_error); |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
624 break; |
71 | 625 case CANCELLED_STATE: |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
626 handler.Cancel(); |
10 | 627 break; |
628 default: | |
629 // do nothing | |
630 return; | |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
631 } |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
632 } |
2 | 633 |
65 | 634 void OnStateChanged() { |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
635 HandlerDescriptor handler; |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
636 while (m_handlers.TryDequeue(out handler)) |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
637 InvokeHandler(handler); |
11 | 638 } |
639 | |
9 | 640 public bool IsExclusive { |
641 get { | |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
642 return m_childrenCount <= 1; |
9 | 643 } |
644 } | |
645 | |
25 | 646 /// <summary> |
647 /// Объединяет несколько обещаний в одно, результатом которого является массив результатов других обещаний. | |
648 /// Если хотябы одно из переданных обещаний не будет выполнено, то новое обещение тоже не будет выполнено. | |
649 /// При отмене нового обещания, переданные обещания также будут отменены, если никто больше на них не подписан. | |
650 /// </summary> | |
651 /// <param name="promises">Список обещаний. Если список пустой, то результирующее обещание возвращается уже выполненным.</param> | |
652 /// <returns>Обещание объединяющее в себе результат переданных обещаний.</returns> | |
653 /// <exception cref="ArgumentNullException"><paramref name="promises"/> не может быть null</exception> | |
30 | 654 public static IPromise<T[]> CreateComposite(IList<IPromise<T>> promises) { |
25 | 655 if (promises == null) |
656 throw new ArgumentNullException(); | |
657 | |
658 // создаем аккумулятор для результатов и результирующее обещание | |
659 var result = new T[promises.Count]; | |
660 var promise = new Promise<T[]>(); | |
661 | |
662 // special case | |
663 if (promises.Count == 0) { | |
664 promise.Resolve(result); | |
665 return promise; | |
666 } | |
667 | |
668 int pending = promises.Count; | |
669 | |
670 for (int i = 0; i < promises.Count; i++) { | |
671 var dest = i; | |
672 | |
33
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
673 if (promises[i] != null) { |
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
674 promises[i].Then( |
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
675 x => { |
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
676 result[dest] = x; |
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
677 if (Interlocked.Decrement(ref pending) == 0) |
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
678 promise.Resolve(result); |
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
679 }, |
72 | 680 e => { |
681 promise.Reject(e); | |
682 return default(T); | |
683 } | |
33
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
684 ); |
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
685 } else { |
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
686 if (Interlocked.Decrement(ref pending) == 0) |
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
687 promise.Resolve(result); |
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
688 } |
25 | 689 } |
690 | |
691 promise.Cancelled( | |
692 () => { | |
33
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
693 foreach (var d in promises) |
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
694 if (d != null && d.IsExclusive) |
25 | 695 d.Cancel(); |
696 } | |
697 ); | |
698 | |
699 return promise; | |
700 } | |
701 | |
33
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 /// Объединяет несколько обещаний в одно. Результирующее обещание будет выполнено при |
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
704 /// выполнении всех указанных обещаний. При этом возвращаемые значения первичных обещаний |
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 /// </summary> |
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
707 /// <param name="promises">Коллекция первичных обещаний, которые будут объеденены в одно.</param> |
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
708 /// <returns>Новое обещание, объединяющее в себе переданные.</returns> |
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
709 /// <remarks> |
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
710 /// Если в коллекции встречаюься <c>null</c>, то они воспринимаются как выполненные обещания. |
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
711 /// </remarks> |
66 | 712 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
|
713 if (promises == null) |
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
714 throw new ArgumentNullException(); |
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
715 if (promises.Count == 0) |
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
716 return Promise<object>.ResultToPromise(null); |
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 int countdown = promises.Count; |
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 var result = new Promise<object>(); |
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 foreach (var d in promises) { |
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
723 if (d == null) { |
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 } else { |
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
727 d.Then(() => { |
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
728 if (Interlocked.Decrement(ref countdown) == 0) |
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
729 result.Resolve(null); |
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
730 }); |
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
731 } |
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 result.Cancelled(() => { |
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
735 foreach (var d in promises) |
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
736 if (d != null && d.IsExclusive) |
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
737 d.Cancel(); |
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
738 }); |
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
739 |
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
740 return result; |
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 |
25 | 743 public static Promise<T> ResultToPromise(T result) { |
744 var p = new Promise<T>(); | |
745 p.Resolve(result); | |
746 return p; | |
747 } | |
748 | |
749 public static Promise<T> ExceptionToPromise(Exception error) { | |
750 if (error == null) | |
751 throw new ArgumentNullException(); | |
752 | |
753 var p = new Promise<T>(); | |
754 p.Reject(error); | |
755 return p; | |
756 } | |
757 | |
33
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
758 #region IPromiseBase explicit implementation |
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
759 |
76 | 760 IPromise IPromise.Then(Action success, ErrorHandler error, Action cancel) { |
761 return Then( | |
762 x => success(), | |
763 e => { | |
764 error(e); | |
765 return default(T); | |
766 }, | |
767 cancel | |
768 ); | |
769 } | |
770 | |
771 IPromise IPromise.Then(Action success, ErrorHandler error) { | |
772 return Then( | |
773 x => success(), | |
774 e => { | |
775 error(e); | |
776 return default(T); | |
777 } | |
778 ); | |
779 } | |
780 | |
781 IPromise IPromise.Then(Action success) { | |
782 return Then(x => success()); | |
783 } | |
784 | |
785 void IPromise.Last(Action success, ErrorHandler error, Action cancel) { | |
786 Last(x => success(), error, cancel); | |
787 } | |
788 | |
789 void IPromise.Last(Action success, ErrorHandler error) { | |
790 Last(x => success(), error, null); | |
791 } | |
792 | |
793 void IPromise.Last(Action success) { | |
794 Last(x => success(), null, null); | |
795 } | |
796 | |
66 | 797 IPromise IPromise.Error(ErrorHandler error) { |
33
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
798 return Error(error); |
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
799 } |
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
800 |
76 | 801 IPromise IPromise.Anyway(Action handler) { |
802 return Anyway(handler); | |
33
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
803 } |
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
804 |
66 | 805 IPromise IPromise.Cancelled(Action handler) { |
33
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
806 return Cancelled(handler); |
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
807 } |
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
808 |
66 | 809 void IPromise.Join() { |
33
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
810 Join(); |
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
811 } |
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
812 |
66 | 813 void IPromise.Join(int timeout) { |
33
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
814 Join(timeout); |
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
815 } |
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
816 |
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
817 #endregion |
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
818 |
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
819 |
b255e4aeef17
removed the reference to the parent from the promise object this allows
cin
parents:
32
diff
changeset
|
820 |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
821 } |
2 | 822 } |