Mercurial > pub > ImplabNet
annotate Implab/Promise.cs @ 19:e3935fdf59a2 promises
Promise is rewritten to use interlocked operations instead of locks
author | cin |
---|---|
date | Sun, 10 Nov 2013 00:21:33 +0400 |
parents | 5a4b735ba669 |
children | 9bf5b23650c9 |
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); |
13 public delegate TNew ResultMapper<in TSrc, out TNew>(TSrc result); | |
14 public delegate Promise<TNew> ChainedOperation<in TSrc, TNew>(TSrc result); | |
2 | 15 |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
16 /// <summary> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
17 /// Класс для асинхронного получения результатов. Так называемое "обещание". |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
18 /// </summary> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
19 /// <typeparam name="T">Тип получаемого результата</typeparam> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
20 /// <remarks> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
21 /// <para>Сервис при обращении к его методу дает обещаиние о выполнении операции, |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
22 /// клиент получив такое обещание может установить ряд обратных вызово для получения |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
23 /// событий выполнения обещания, тоесть завершения операции и предоставлении результатов.</para> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
24 /// <para> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
25 /// Обещение может быть как выполнено, так и выполнено с ошибкой. Для подписки на |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
26 /// данные события клиент должен использовать методы <c>Then</c>. |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
27 /// </para> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
28 /// <para> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
29 /// Сервис, в свою очередь, по окончанию выполнения операции (возможно с ошибкой), |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
30 /// использует методы <c>Resolve</c> либо <c>Reject</c> для оповещения клиетна о |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
31 /// выполнении обещания. |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
32 /// </para> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
33 /// <para> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
34 /// Если сервер успел выполнить обещание еще до того, как клиент на него подписался, |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
35 /// то в момент подписки клиента будут вызваны соответсвующие события в синхронном |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
36 /// режиме и клиент будет оповещен в любом случае. Иначе, обработчики добавляются в |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
37 /// список в порядке подписания и в этом же порядке они будут вызваны при выполнении |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
38 /// обещания. |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
39 /// </para> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
40 /// <para> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
41 /// Обрабатывая результаты обещания можно преобразовывать результаты либо инициировать |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
42 /// связанные асинхронные операции, которые также возвращают обещания. Для этого следует |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
43 /// использовать соответствующую форму методе <c>Then</c>. |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
44 /// </para> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
45 /// <para> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
46 /// Также хорошим правилом является то, что <c>Resolve</c> и <c>Reject</c> должен вызывать |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
47 /// только инициатор обещания иначе могут возникнуть противоречия. |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
48 /// </para> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
49 /// </remarks> |
9 | 50 public class Promise<T> : IPromise { |
2 | 51 |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
52 struct HandlerDescriptor { |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
53 public ResultHandler<T> resultHandler; |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
54 public ErrorHandler errorHandler; |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
55 public Action cancellHandler; |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
56 |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
57 public void Resolve(T result) { |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
58 if (resultHandler != null) |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
59 try { |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
60 resultHandler(result); |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
61 } catch (Exception e) { |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
62 Reject(e); |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
63 } |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
64 } |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
65 |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
66 public void Reject(Exception err) { |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
67 if (errorHandler != null) |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
68 try { |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
69 errorHandler(err); |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
70 } catch { |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
71 } |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
72 } |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
73 |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
74 public void Cancel() { |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
75 if (cancellHandler != null) |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
76 try { |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
77 cancellHandler(); |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
78 } catch { |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
79 } |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
80 } |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
81 } |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
82 |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
83 const int UnresolvedSate = 0; |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
84 const int TransitionalState = 1; |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
85 const int ResolvedState = 2; |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
86 const int RejectedState = 3; |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
87 const int CancelledState = 4; |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
88 |
10 | 89 readonly IPromise m_parent; |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
90 readonly bool m_cancellable; |
9 | 91 |
10 | 92 int m_childrenCount = 0; |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
93 int m_state; |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
94 T m_result; |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
95 Exception m_error; |
9 | 96 |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
97 readonly MTQueue<HandlerDescriptor> m_handlers = new MTQueue<HandlerDescriptor>(); |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
98 |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
99 public Promise() { |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
100 m_cancellable = true; |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
101 } |
2 | 102 |
9 | 103 public Promise(IPromise parent, bool cancellable) { |
7 | 104 m_cancellable = cancellable; |
105 m_parent = parent; | |
106 } | |
107 | |
10 | 108 void InternalCancel() { |
109 // don't try to cancel parent :) | |
110 Cancel(false); | |
111 } | |
2 | 112 |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
113 bool BeginTransit() { |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
114 return UnresolvedSate == Interlocked.CompareExchange(ref m_state, TransitionalState, UnresolvedSate); |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
115 } |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
116 |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
117 void CompleteTransit(int state) { |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
118 if (TransitionalState != Interlocked.CompareExchange(ref m_state, state, TransitionalState)) |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
119 throw new InvalidOperationException("Can't complete transition when the object isn't in the transitional state"); |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
120 } |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
121 |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
122 public bool IsResolved { |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
123 get { |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
124 return m_state > 1; |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
125 } |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
126 } |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
127 |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
128 public bool IsCancelled { |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
129 get { |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
130 return m_state == CancelledState; |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
131 } |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
132 } |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
133 |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
134 /// <summary> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
135 /// Выполняет обещание, сообщая об успешном выполнении. |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
136 /// </summary> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
137 /// <param name="result">Результат выполнения.</param> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
138 /// <exception cref="InvalidOperationException">Данное обещание уже выполнено</exception> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
139 public void Resolve(T result) { |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
140 if (BeginTransit()) { |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
141 m_result = result; |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
142 CompleteTransit(ResolvedState); |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
143 OnStateChanged(); |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
144 } else if (m_state != CancelledState) |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
145 throw new InvalidOperationException("The promise is already resolved"); |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
146 } |
2 | 147 |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
148 /// <summary> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
149 /// Выполняет обещание, сообщая об ошибке |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
150 /// </summary> |
16 | 151 /// <remarks> |
152 /// Поскольку обещание должно работать в многопточной среде, при его выполнении сразу несколько потоков | |
153 /// могу вернуть ошибку, при этом только первая будет использована в качестве результата, остальные | |
154 /// будут проигнорированы. | |
155 /// </remarks> | |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
156 /// <param name="error">Исключение возникшее при выполнении операции</param> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
157 /// <exception cref="InvalidOperationException">Данное обещание уже выполнено</exception> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
158 public void Reject(Exception error) { |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
159 if (BeginTransit()) { |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
160 m_error = error; |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
161 CompleteTransit(RejectedState); |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
162 OnStateChanged(); |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
163 } else if (m_state == ResolvedState) |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
164 throw new InvalidOperationException("The promise is already resolved"); |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
165 } |
2 | 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 /// <returns><c>true</c> Операция была отменена, обработчики не будут вызваны.<c>false</c> отмена не возможна, поскольку обещание уже выполнено и обработчики отработали.</returns> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
171 public bool Cancel() { |
9 | 172 return Cancel(true); |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
173 } |
2 | 174 |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
175 /// <summary> |
11 | 176 /// Adds new handlers to this promise. |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
177 /// </summary> |
11 | 178 /// <param name="success">The handler of the successfully completed operation. |
179 /// This handler will recieve an operation result as a parameter.</param> | |
180 /// <param name="error">Handles an exception that may occur during the operation.</param> | |
181 /// <returns>The new promise chained to this one.</returns> | |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
182 public Promise<T> Then(ResultHandler<T> success, ErrorHandler error) { |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
183 if (success == null && error == null) |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
184 return this; |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
185 |
11 | 186 var medium = new Promise<T>(this, true); |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
187 |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
188 ResultHandler<T> resultHandler; |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
189 if (success != null) |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
190 resultHandler = x => { |
10 | 191 success(x); |
192 medium.Resolve(x); | |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
193 }; |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
194 else |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
195 resultHandler = medium.Resolve; |
2 | 196 |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
197 ErrorHandler errorHandler; |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
198 if (error != null) |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
199 errorHandler = x => { |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
200 try { |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
201 error(x); |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
202 } catch { } |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
203 medium.Reject(x); |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
204 }; |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
205 else |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
206 errorHandler = medium.Reject; |
2 | 207 |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
208 AddHandler(resultHandler, errorHandler, medium.InternalCancel); |
2 | 209 |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
210 return medium; |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
211 } |
2 | 212 |
11 | 213 /// <summary> |
214 /// Adds new handlers to this promise. | |
215 /// </summary> | |
216 /// <param name="success">The handler of the successfully completed operation. | |
217 /// This handler will recieve an operation result as a parameter.</param> | |
218 /// <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> | |
219 /// <returns>The new promise chained to this one.</returns> | |
220 public Promise<T> Then(ResultHandler<T> success, ErrorHandler<T> error) { | |
221 if (success == null && error == null) | |
222 return this; | |
223 | |
224 var medium = new Promise<T>(this, true); | |
225 | |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
226 ResultHandler<T> resultHandler; |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
227 ErrorHandler errorHandler; |
11 | 228 |
229 if (success != null) | |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
230 resultHandler = x => { |
11 | 231 success(x); |
232 medium.Resolve(x); | |
233 }; | |
234 else | |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
235 resultHandler = medium.Resolve; |
11 | 236 |
237 if (error != null) | |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
238 errorHandler = x => { |
11 | 239 try { |
240 medium.Resolve(error(x)); | |
241 } catch { } | |
242 medium.Reject(x); | |
243 }; | |
244 else | |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
245 errorHandler = medium.Reject; |
11 | 246 |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
247 AddHandler(resultHandler, errorHandler, medium.InternalCancel); |
11 | 248 |
249 return medium; | |
250 } | |
251 | |
252 | |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
253 public Promise<T> Then(ResultHandler<T> success) { |
11 | 254 if (success == null) |
255 return this; | |
256 | |
257 var medium = new Promise<T>(this, true); | |
258 | |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
259 ResultHandler<T> resultHandler; |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
260 |
11 | 261 if (success != null) |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
262 resultHandler = x => { |
11 | 263 success(x); |
264 medium.Resolve(x); | |
265 }; | |
266 else | |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
267 resultHandler = medium.Resolve; |
11 | 268 |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
269 AddHandler(resultHandler, medium.Reject, medium.InternalCancel); |
11 | 270 |
271 return medium; | |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
272 } |
2 | 273 |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
274 public Promise<T> Error(ErrorHandler error) { |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
275 return Then(null, error); |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
276 } |
2 | 277 |
11 | 278 /// <summary> |
279 /// Handles error and allows to keep the promise. | |
280 /// </summary> | |
281 /// <remarks> | |
282 /// If the specified handler throws an exception, this exception will be used to reject the promise. | |
283 /// </remarks> | |
284 /// <param name="handler">The error handler which returns the result of the promise.</param> | |
285 /// <returns>New promise.</returns> | |
286 public Promise<T> Error(ErrorHandler<T> handler) { | |
287 if (handler == null) | |
288 return this; | |
289 | |
290 var medium = new Promise<T>(this, true); | |
291 | |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
292 AddHandler( |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
293 null, |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
294 e => { |
11 | 295 try { |
296 medium.Resolve(handler(e)); | |
297 } catch (Exception e2) { | |
298 medium.Reject(e2); | |
299 } | |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
300 }, |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
301 medium.InternalCancel |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
302 ); |
11 | 303 |
304 return medium; | |
305 } | |
306 | |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
307 public Promise<T> Anyway(Action handler) { |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
308 if (handler == null) |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
309 return this; |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
310 |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
311 var medium = new Promise<T>(); |
2 | 312 |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
313 AddHandler( |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
314 x => { |
10 | 315 // to avoid handler being called multiple times we handle exception by ourselfs |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
316 try { |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
317 handler(); |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
318 medium.Resolve(x); |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
319 } catch (Exception e) { |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
320 medium.Reject(e); |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
321 } |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
322 }, |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
323 |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
324 e => { |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
325 try { |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
326 handler(); |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
327 } catch { } |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
328 medium.Reject(e); |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
329 }, |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
330 |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
331 medium.InternalCancel |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
332 ); |
2 | 333 |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
334 return medium; |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
335 } |
2 | 336 |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
337 /// <summary> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
338 /// Позволяет преобразовать результат выполения операции к новому типу. |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
339 /// </summary> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
340 /// <typeparam name="TNew">Новый тип результата.</typeparam> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
341 /// <param name="mapper">Преобразование результата к новому типу.</param> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
342 /// <param name="error">Обработчик ошибки. Данный обработчик получит |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
343 /// исключение возникшее при выполнении операции.</param> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
344 /// <returns>Новое обещание, которое будет выполнено при выполнении исходного обещания.</returns> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
345 public Promise<TNew> Map<TNew>(ResultMapper<T, TNew> mapper, ErrorHandler error) { |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
346 if (mapper == null) |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
347 throw new ArgumentNullException("mapper"); |
2 | 348 |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
349 // создаем прицепленное обещание |
10 | 350 var chained = new Promise<TNew>(); |
2 | 351 |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
352 ResultHandler<T> resultHandler = result => chained.Resolve(mapper(result)); |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
353 ErrorHandler errorHandler = delegate(Exception e) { |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
354 if (error != null) |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
355 try { |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
356 error(e); |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
357 } catch { } |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
358 // в случае ошибки нужно передать исключение дальше по цепочке |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
359 chained.Reject(e); |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
360 }; |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
361 |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
362 |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
363 AddHandler( |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
364 resultHandler, |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
365 errorHandler, |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
366 chained.InternalCancel |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
367 ); |
2 | 368 |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
369 return chained; |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
370 } |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
371 |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
372 public Promise<TNew> Map<TNew>(ResultMapper<T, TNew> mapper) { |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
373 return Map(mapper, null); |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
374 } |
2 | 375 |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
376 /// <summary> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
377 /// Сцепляет несколько аснхронных операций. Указанная асинхронная операция будет вызвана после |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
378 /// выполнения текущей, а результат текущей операции может быть использован для инициализации |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
379 /// новой операции. |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
380 /// </summary> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
381 /// <typeparam name="TNew">Тип результата указанной асинхронной операции.</typeparam> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
382 /// <param name="chained">Асинхронная операция, которая должна будет начаться после выполнения текущей.</param> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
383 /// <param name="error">Обработчик ошибки. Данный обработчик получит |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
384 /// исключение возникшее при выполнении текуещй операции.</param> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
385 /// <returns>Новое обещание, которое будет выполнено по окончанию указанной аснхронной операции.</returns> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
386 public Promise<TNew> Chain<TNew>(ChainedOperation<T, TNew> chained, ErrorHandler error) { |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
387 |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
388 // проблема в том, что на момент связывания еще не начата асинхронная операция, поэтому нужно |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
389 // создать посредника, к которому будут подвызяваться следующие обработчики. |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
390 // когда будет выполнена реальная асинхронная операция, она обратиться к посреднику, чтобы |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
391 // передать через него результаты работы. |
10 | 392 var medium = new Promise<TNew>(this, true); |
2 | 393 |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
394 ResultHandler<T> resultHandler = delegate(T result) { |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
395 if (medium.IsCancelled) |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
396 return; |
10 | 397 |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
398 var promise = chained(result); |
10 | 399 |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
400 // notify chained operation that it's not needed |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
401 medium.Cancelled(() => promise.Cancel()); |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
402 promise.Then( |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
403 x => medium.Resolve(x), |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
404 e => medium.Reject(e) |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
405 ); |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
406 }; |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
407 |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
408 ErrorHandler errorHandler = delegate(Exception e) { |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
409 if (error != null) |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
410 error(e); |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
411 // в случае ошибки нужно передать исключение дальше по цепочке |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
412 medium.Reject(e); |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
413 }; |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
414 |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
415 AddHandler( |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
416 resultHandler, |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
417 errorHandler, |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
418 medium.InternalCancel |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
419 ); |
2 | 420 |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
421 return medium; |
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 public Promise<TNew> Chain<TNew>(ChainedOperation<T, TNew> chained) { |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
425 return Chain(chained, null); |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
426 } |
2 | 427 |
10 | 428 public Promise<T> Cancelled(Action handler) { |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
429 AddHandler(null, null, handler); |
10 | 430 return this; |
431 } | |
432 | |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
433 public Promise<T> Finally(Action handler) { |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
434 if (handler == null) |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
435 throw new ArgumentNullException("handler"); |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
436 AddHandler( |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
437 x => handler(), |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
438 e => handler(), |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
439 handler |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
440 ); |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
441 return this; |
10 | 442 } |
443 | |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
444 /// <summary> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
445 /// Дожидается отложенного обещания и в случае успеха, возвращает |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
446 /// его, результат, в противном случае бросает исключение. |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
447 /// </summary> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
448 /// <remarks> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
449 /// <para> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
450 /// Если ожидание обещания было прервано по таймауту, это не значит, |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
451 /// что обещание было отменено или что-то в этом роде, это только |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
452 /// означает, что мы его не дождались, однако все зарегистрированные |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
453 /// обработчики, как были так остались и они будут вызваны, когда |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
454 /// обещание будет выполнено. |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
455 /// </para> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
456 /// <para> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
457 /// Такое поведение вполне оправдано поскольку таймаут может истечь |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
458 /// в тот момент, когда началась обработка цепочки обработчиков, и |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
459 /// к тому же текущее обещание может стоять в цепочке обещаний и его |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
460 /// отклонение может привести к непрогнозируемому результату. |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
461 /// </para> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
462 /// </remarks> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
463 /// <param name="timeout">Время ожидания</param> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
464 /// <returns>Результат выполнения обещания</returns> |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
465 public T Join(int timeout) { |
10 | 466 var evt = new ManualResetEvent(false); |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
467 Anyway(() => evt.Set()); |
10 | 468 Cancelled(() => evt.Set()); |
2 | 469 |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
470 if (!evt.WaitOne(timeout, true)) |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
471 throw new TimeoutException(); |
2 | 472 |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
473 switch (m_state) { |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
474 case ResolvedState: |
10 | 475 return m_result; |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
476 case CancelledState: |
10 | 477 throw new OperationCanceledException(); |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
478 case RejectedState: |
10 | 479 throw new TargetInvocationException(m_error); |
480 default: | |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
481 throw new ApplicationException(String.Format("Invalid promise state {0}", m_state)); |
10 | 482 } |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
483 } |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
484 |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
485 public T Join() { |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
486 return Join(Timeout.Infinite); |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
487 } |
2 | 488 |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
489 void AddHandler(ResultHandler<T> success, ErrorHandler error, Action cancel) { |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
490 Interlocked.Increment(ref m_childrenCount); |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
491 |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
492 HandlerDescriptor handler = new HandlerDescriptor { |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
493 resultHandler = success, |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
494 errorHandler = error, |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
495 cancellHandler = cancel |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
496 }; |
2 | 497 |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
498 bool queued; |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
499 |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
500 if (!IsResolved) { |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
501 m_handlers.Enqueue(handler); |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
502 queued = true; |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
503 } else { |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
504 // 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
|
505 queued = false; |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
506 InvokeHandler(handler); |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
507 } |
2 | 508 |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
509 if (queued && IsResolved && m_handlers.TryDequeue(out handler)) |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
510 // 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
|
511 // 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
|
512 // therefore we will fetch a handler from the queue and execute it |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
513 // note that fetched handler may be not the one we have added |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
514 InvokeHandler(handler); |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
515 |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
516 } |
2 | 517 |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
518 void InvokeHandler(HandlerDescriptor handler) { |
10 | 519 switch (m_state) { |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
520 case ResolvedState: |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
521 handler.Resolve(m_result); |
10 | 522 break; |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
523 case RejectedState: |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
524 handler.Reject(m_error); |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
525 break; |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
526 case CancelledState: |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
527 handler.Cancel(); |
10 | 528 break; |
529 default: | |
530 // do nothing | |
531 return; | |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
532 } |
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
533 } |
2 | 534 |
11 | 535 protected virtual void OnStateChanged() { |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
536 HandlerDescriptor handler; |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
537 while (m_handlers.TryDequeue(out handler)) |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
538 InvokeHandler(handler); |
11 | 539 } |
540 | |
2 | 541 |
9 | 542 |
543 public bool IsExclusive { | |
544 get { | |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
545 return m_childrenCount <= 1; |
9 | 546 } |
547 } | |
548 | |
11 | 549 protected bool Cancel(bool dependencies) { |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
550 if (BeginTransit()) { |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
551 CompleteTransit(CancelledState); |
10 | 552 OnStateChanged(); |
9 | 553 |
19
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
554 if (dependencies && m_parent != null && m_parent.IsExclusive) |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
555 m_parent.Cancel(); |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
556 |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
557 return true; |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
558 } else { |
e3935fdf59a2
Promise is rewritten to use interlocked operations instead of locks
cin
parents:
16
diff
changeset
|
559 return false; |
9 | 560 } |
561 } | |
15 | 562 |
6
dfa21d507bc5
*refactoring: Promise.Then now returns a new chained promise
cin
parents:
2
diff
changeset
|
563 } |
2 | 564 } |