annotate Implab/Promise.cs @ 9:c82e0dfbb4dd promises

sync
author cin
date Sat, 02 Nov 2013 00:55:47 +0400
parents 7ea9363fef6c
children aa33d0bb8c0c
Ignore whitespace changes - Everywhere: Within whitespace: At end of lines:
rev   line source
2
aa367305156b small fixes
cin
parents: 1
diff changeset
1 using System;
aa367305156b small fixes
cin
parents: 1
diff changeset
2 using System.Collections.Generic;
aa367305156b small fixes
cin
parents: 1
diff changeset
3 using System.Linq;
aa367305156b small fixes
cin
parents: 1
diff changeset
4 using System.Reflection;
aa367305156b small fixes
cin
parents: 1
diff changeset
5 using System.Text;
aa367305156b small fixes
cin
parents: 1
diff changeset
6 using System.Diagnostics;
aa367305156b small fixes
cin
parents: 1
diff changeset
7 using System.Threading;
aa367305156b small fixes
cin
parents: 1
diff changeset
8
aa367305156b small fixes
cin
parents: 1
diff changeset
9 namespace Implab {
aa367305156b small fixes
cin
parents: 1
diff changeset
10
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
11 public delegate void ErrorHandler(Exception e);
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
12
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
13 public delegate void ResultHandler<T>(T result);
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
14 public delegate TNew ResultMapper<TSrc, TNew>(TSrc result);
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
15 public delegate Promise<TNew> ChainedOperation<TSrc, TNew>(TSrc result);
2
aa367305156b small fixes
cin
parents: 1
diff changeset
16
6
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 /// Класс для асинхронного получения результатов. Так называемое "обещание".
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
19 /// </summary>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
20 /// <typeparam name="T">Тип получаемого результата</typeparam>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
21 /// <remarks>
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 /// клиент получив такое обещание может установить ряд обратных вызово для получения
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 /// <para>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
26 /// Обещение может быть как выполнено, так и выполнено с ошибкой. Для подписки на
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
27 /// данные события клиент должен использовать методы <c>Then</c>.
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 /// <para>
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 /// использует методы <c>Resolve</c> либо <c>Reject</c> для оповещения клиетна о
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
32 /// выполнении обещания.
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 /// <para>
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 /// обещания.
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 /// <para>
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 /// связанные асинхронные операции, которые также возвращают обещания. Для этого следует
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
44 /// использовать соответствующую форму методе <c>Then</c>.
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 /// <para>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
47 /// Также хорошим правилом является то, что <c>Resolve</c> и <c>Reject</c> должен вызывать
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
48 /// только инициатор обещания иначе могут возникнуть противоречия.
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
49 /// </para>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
50 /// </remarks>
9
cin
parents: 7
diff changeset
51 public class Promise<T> : IPromise {
2
aa367305156b small fixes
cin
parents: 1
diff changeset
52
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
53 struct ResultHandlerInfo {
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
54 public ResultHandler<T> resultHandler;
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
55 public ErrorHandler errorHandler;
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
56 }
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
57
9
cin
parents: 7
diff changeset
58 IPromise m_parent;
cin
parents: 7
diff changeset
59
cin
parents: 7
diff changeset
60 LinkedList<ResultHandlerInfo> m_resultHandlers = new LinkedList<ResultHandlerInfo>();
cin
parents: 7
diff changeset
61 LinkedList<Action> m_cancelHandlers = new LinkedList<Action>();
cin
parents: 7
diff changeset
62
cin
parents: 7
diff changeset
63 object m_lock = new Object();
cin
parents: 7
diff changeset
64 bool m_cancellable;
cin
parents: 7
diff changeset
65
7
7ea9363fef6c inital progress handling
cin
parents: 6
diff changeset
66 PromiseState m_state;
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
67 T m_result;
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
68 Exception m_error;
9
cin
parents: 7
diff changeset
69
7
7ea9363fef6c inital progress handling
cin
parents: 6
diff changeset
70 int m_childrenCount;
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
71
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
72 public Promise() {
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
73 m_cancellable = true;
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
74 }
2
aa367305156b small fixes
cin
parents: 1
diff changeset
75
9
cin
parents: 7
diff changeset
76 public Promise(IPromise parent, bool cancellable) {
7
7ea9363fef6c inital progress handling
cin
parents: 6
diff changeset
77 m_cancellable = cancellable;
7ea9363fef6c inital progress handling
cin
parents: 6
diff changeset
78 m_parent = parent;
7ea9363fef6c inital progress handling
cin
parents: 6
diff changeset
79 }
7ea9363fef6c inital progress handling
cin
parents: 6
diff changeset
80
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
81 /// <summary>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
82 /// Событие, возникающее при отмене асинхронной операции.
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
83 /// </summary>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
84 /// <description>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
85 /// Как правило используется для оповещения объекта, выполняющего асинхронную операцию, о том, что ее следует отменить.
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
86 /// </description>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
87 public event EventHandler Cancelled;
2
aa367305156b small fixes
cin
parents: 1
diff changeset
88
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
89 /// <summary>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
90 /// Выполняет обещание, сообщая об успешном выполнении.
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
91 /// </summary>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
92 /// <param name="result">Результат выполнения.</param>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
93 /// <exception cref="InvalidOperationException">Данное обещание уже выполнено</exception>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
94 public void Resolve(T result) {
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
95 lock (this) {
7
7ea9363fef6c inital progress handling
cin
parents: 6
diff changeset
96 if (m_state == PromiseState.Cancelled)
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
97 return;
7
7ea9363fef6c inital progress handling
cin
parents: 6
diff changeset
98 if (m_state != PromiseState.Unresolved)
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
99 throw new InvalidOperationException("The promise is already resolved");
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
100 m_result = result;
7
7ea9363fef6c inital progress handling
cin
parents: 6
diff changeset
101 m_state = PromiseState.Resolved;
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
102 }
2
aa367305156b small fixes
cin
parents: 1
diff changeset
103
9
cin
parents: 7
diff changeset
104 // state has been changed to rejected new handlers can't be added
cin
parents: 7
diff changeset
105
cin
parents: 7
diff changeset
106 foreach (var handler in m_resultHandlers)
cin
parents: 7
diff changeset
107 InvokeHandler(handler);
cin
parents: 7
diff changeset
108
cin
parents: 7
diff changeset
109 /* ResultHandlerInfo handler;
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
110 while (FetchNextHandler(out handler))
9
cin
parents: 7
diff changeset
111 InvokeHandler(handler); */
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
112 }
2
aa367305156b small fixes
cin
parents: 1
diff changeset
113
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
114 /// <summary>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
115 /// Выполняет обещание, сообщая об ошибке
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
116 /// </summary>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
117 /// <param name="error">Исключение возникшее при выполнении операции</param>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
118 /// <exception cref="InvalidOperationException">Данное обещание уже выполнено</exception>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
119 public void Reject(Exception error) {
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
120 lock (this) {
7
7ea9363fef6c inital progress handling
cin
parents: 6
diff changeset
121 if (m_state == PromiseState.Cancelled)
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
122 return;
7
7ea9363fef6c inital progress handling
cin
parents: 6
diff changeset
123 if (m_state != PromiseState.Unresolved)
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
124 throw new InvalidOperationException("The promise is already resolved");
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
125 m_error = error;
7
7ea9363fef6c inital progress handling
cin
parents: 6
diff changeset
126 m_state = PromiseState.Rejected;
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
127 }
2
aa367305156b small fixes
cin
parents: 1
diff changeset
128
9
cin
parents: 7
diff changeset
129 // state has been changed to rejected new handlers can't be added
cin
parents: 7
diff changeset
130
cin
parents: 7
diff changeset
131 foreach (var handler in m_resultHandlers)
cin
parents: 7
diff changeset
132 InvokeHandler(handler);
cin
parents: 7
diff changeset
133
cin
parents: 7
diff changeset
134 /*ResultHandlerInfo handler;
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
135 while (FetchNextHandler(out handler))
9
cin
parents: 7
diff changeset
136 InvokeHandler(handler);*/
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
137 }
2
aa367305156b small fixes
cin
parents: 1
diff changeset
138
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
139 /// <summary>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
140 /// Отменяет операцию, если это возможно.
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
141 /// </summary>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
142 /// <returns><c>true</c> Операция была отменена, обработчики не будут вызваны.<c>false</c> отмена не возможна, поскольку обещание уже выполнено и обработчики отработали.</returns>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
143 public bool Cancel() {
9
cin
parents: 7
diff changeset
144 return Cancel(true);
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
145 }
2
aa367305156b small fixes
cin
parents: 1
diff changeset
146
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
147 /// <summary>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
148 /// Добавляет обработчики событий выполнения обещания.
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
149 /// </summary>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
150 /// <param name="success">Обработчик успешного выполнения обещания.
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
151 /// Данному обработчику будет передан результат выполнения операции.</param>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
152 /// <param name="error">Обработчик ошибки. Данный обработчик получит
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
153 /// исключение возникшее при выполнении операции.</param>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
154 /// <returns>Само обещание</returns>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
155 public Promise<T> Then(ResultHandler<T> success, ErrorHandler error) {
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
156 if (success == null && error == null)
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
157 return this;
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
158
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
159 var medium = new Promise<T>();
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
160
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
161 var handlerInfo = new ResultHandlerInfo();
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
162
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
163 if (success != null)
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
164 handlerInfo.resultHandler = x => {
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
165 try {
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
166 success(x);
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
167 medium.Resolve(x);
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
168 } catch (Exception e) {
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
169 medium.Reject(e);
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
170 }
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
171 };
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
172 else
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
173 handlerInfo.resultHandler = x => medium.Resolve(x);
2
aa367305156b small fixes
cin
parents: 1
diff changeset
174
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
175 if (error != null)
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
176 handlerInfo.errorHandler = x => {
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
177 try {
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
178 error(x);
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
179 } catch { }
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
180 medium.Reject(x);
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
181 };
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
182 else
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
183 handlerInfo.errorHandler = x => medium.Reject(x);
2
aa367305156b small fixes
cin
parents: 1
diff changeset
184
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
185 AddHandler(handlerInfo);
2
aa367305156b small fixes
cin
parents: 1
diff changeset
186
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
187 return medium;
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
188 }
2
aa367305156b small fixes
cin
parents: 1
diff changeset
189
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
190 public Promise<T> Then(ResultHandler<T> success) {
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
191 return Then(success, null);
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
192 }
2
aa367305156b small fixes
cin
parents: 1
diff changeset
193
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
194 public Promise<T> Error(ErrorHandler error) {
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
195 return Then(null, error);
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
196 }
2
aa367305156b small fixes
cin
parents: 1
diff changeset
197
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
198 public Promise<T> Anyway(Action handler) {
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
199 if (handler == null)
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
200 return this;
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
201
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
202 var medium = new Promise<T>();
2
aa367305156b small fixes
cin
parents: 1
diff changeset
203
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
204 AddHandler(new ResultHandlerInfo {
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
205 resultHandler = x => {
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
206 try {
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
207 handler();
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
208 medium.Resolve(x);
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
209 } catch (Exception e) {
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
210 medium.Reject(e);
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
211 }
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
212 },
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
213 errorHandler = x => {
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
214 try {
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
215 handler();
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
216 } catch { }
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
217 medium.Reject(x);
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
218 }
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
219 });
2
aa367305156b small fixes
cin
parents: 1
diff changeset
220
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
221 return medium;
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
222 }
2
aa367305156b small fixes
cin
parents: 1
diff changeset
223
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
224 /// <summary>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
225 /// Позволяет преобразовать результат выполения операции к новому типу.
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
226 /// </summary>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
227 /// <typeparam name="TNew">Новый тип результата.</typeparam>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
228 /// <param name="mapper">Преобразование результата к новому типу.</param>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
229 /// <param name="error">Обработчик ошибки. Данный обработчик получит
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
230 /// исключение возникшее при выполнении операции.</param>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
231 /// <returns>Новое обещание, которое будет выполнено при выполнении исходного обещания.</returns>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
232 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
233 if (mapper == null)
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
234 throw new ArgumentNullException("mapper");
2
aa367305156b small fixes
cin
parents: 1
diff changeset
235
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
236 // создаем прицепленное обещание
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
237 Promise<TNew> chained = new Promise<TNew>();
2
aa367305156b small fixes
cin
parents: 1
diff changeset
238
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
239 AddHandler(new ResultHandlerInfo() {
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
240 resultHandler = delegate(T result) {
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
241 try {
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
242 // если преобразование выдаст исключение, то сработает reject сцепленного deferred
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
243 chained.Resolve(mapper(result));
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
244 } catch (Exception e) {
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
245 chained.Reject(e);
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
246 }
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
247 },
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
248 errorHandler = delegate(Exception e) {
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
249 if (error != null)
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
250 error(e);
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
251 // в случае ошибки нужно передать исключение дальше по цепочке
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
252 chained.Reject(e);
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
253 }
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
254 });
2
aa367305156b small fixes
cin
parents: 1
diff changeset
255
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
256 return chained;
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
257 }
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
258
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
259 public Promise<TNew> Map<TNew>(ResultMapper<T, TNew> mapper) {
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
260 return Map(mapper, null);
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
261 }
2
aa367305156b small fixes
cin
parents: 1
diff changeset
262
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
263 /// <summary>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
264 /// Сцепляет несколько аснхронных операций. Указанная асинхронная операция будет вызвана после
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
265 /// выполнения текущей, а результат текущей операции может быть использован для инициализации
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
266 /// новой операции.
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
267 /// </summary>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
268 /// <typeparam name="TNew">Тип результата указанной асинхронной операции.</typeparam>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
269 /// <param name="chained">Асинхронная операция, которая должна будет начаться после выполнения текущей.</param>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
270 /// <param name="error">Обработчик ошибки. Данный обработчик получит
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
271 /// исключение возникшее при выполнении текуещй операции.</param>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
272 /// <returns>Новое обещание, которое будет выполнено по окончанию указанной аснхронной операции.</returns>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
273 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
274
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
275 // проблема в том, что на момент связывания еще не начата асинхронная операция, поэтому нужно
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
276 // создать посредника, к которому будут подвызяваться следующие обработчики.
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
277 // когда будет выполнена реальная асинхронная операция, она обратиться к посреднику, чтобы
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
278 // передать через него результаты работы.
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
279 Promise<TNew> medium = new Promise<TNew>();
2
aa367305156b small fixes
cin
parents: 1
diff changeset
280
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
281 AddHandler(new ResultHandlerInfo() {
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
282 resultHandler = delegate(T result) {
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
283 try {
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
284 chained(result).Then(
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
285 x => medium.Resolve(x),
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
286 e => medium.Reject(e)
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
287 );
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
288 } catch (Exception e) {
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
289 // если сцепленное действие выдало исключение вместо обещания, то передаем ошибку по цепочке
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
290 medium.Reject(e);
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
291 }
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
292 },
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
293 errorHandler = delegate(Exception e) {
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
294 if (error != null)
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
295 error(e);
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
296 // в случае ошибки нужно передать исключение дальше по цепочке
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
297 medium.Reject(e);
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
298 }
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
299 });
2
aa367305156b small fixes
cin
parents: 1
diff changeset
300
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
301 return medium;
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
302 }
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
303
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
304 public Promise<TNew> Chain<TNew>(ChainedOperation<T, TNew> chained) {
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
305 return Chain(chained, null);
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
306 }
2
aa367305156b small fixes
cin
parents: 1
diff changeset
307
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
308 /// <summary>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
309 /// Дожидается отложенного обещания и в случае успеха, возвращает
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 /// </summary>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
312 /// <remarks>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
313 /// <para>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
314 /// Если ожидание обещания было прервано по таймауту, это не значит,
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
315 /// что обещание было отменено или что-то в этом роде, это только
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
316 /// означает, что мы его не дождались, однако все зарегистрированные
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
317 /// обработчики, как были так остались и они будут вызваны, когда
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
318 /// обещание будет выполнено.
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
319 /// </para>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
320 /// <para>
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 /// в тот момент, когда началась обработка цепочки обработчиков, и
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
323 /// к тому же текущее обещание может стоять в цепочке обещаний и его
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
324 /// отклонение может привести к непрогнозируемому результату.
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
325 /// </para>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
326 /// </remarks>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
327 /// <param name="timeout">Время ожидания</param>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
328 /// <returns>Результат выполнения обещания</returns>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
329 public T Join(int timeout) {
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
330 ManualResetEvent evt = new ManualResetEvent(false);
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
331 Anyway(() => evt.Set());
2
aa367305156b small fixes
cin
parents: 1
diff changeset
332
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
333 if (!evt.WaitOne(timeout, true))
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
334 throw new TimeoutException();
2
aa367305156b small fixes
cin
parents: 1
diff changeset
335
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
336 if (m_error != null)
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
337 throw new TargetInvocationException(m_error);
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
338 else
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
339 return m_result;
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
340 }
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
341
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
342 public T Join() {
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
343 return Join(Timeout.Infinite);
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
344 }
2
aa367305156b small fixes
cin
parents: 1
diff changeset
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 /// их больше не осталось - ставит состояние "разрешено".
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
349 /// </summary>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
350 /// <param name="handler">Информация об обработчике</param>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
351 /// <returns>Признак того, что еще остались обработчики в очереди</returns>
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
352 bool FetchNextHandler(out ResultHandlerInfo handler) {
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
353 handler = default(ResultHandlerInfo);
2
aa367305156b small fixes
cin
parents: 1
diff changeset
354
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
355 lock (this) {
7
7ea9363fef6c inital progress handling
cin
parents: 6
diff changeset
356 Debug.Assert(m_state != PromiseState.Unresolved);
2
aa367305156b small fixes
cin
parents: 1
diff changeset
357
9
cin
parents: 7
diff changeset
358 if (m_resultHandlers.Count > 0) {
cin
parents: 7
diff changeset
359 handler = m_resultHandlers.First.Value;
cin
parents: 7
diff changeset
360 m_resultHandlers.RemoveFirst();
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
361 return true;
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
362 } else {
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
363 return false;
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
364 }
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
365 }
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
366 }
2
aa367305156b small fixes
cin
parents: 1
diff changeset
367
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
368 void AddHandler(ResultHandlerInfo handler) {
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
369 bool invokeRequired = false;
2
aa367305156b small fixes
cin
parents: 1
diff changeset
370
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
371 lock (this) {
7
7ea9363fef6c inital progress handling
cin
parents: 6
diff changeset
372 if (m_state == PromiseState.Unresolved)
9
cin
parents: 7
diff changeset
373 m_resultHandlers.AddLast(handler);
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
374 else
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
375 invokeRequired = true;
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
376 }
2
aa367305156b small fixes
cin
parents: 1
diff changeset
377
6
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 if (invokeRequired)
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
380 InvokeHandler(handler);
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
381 }
2
aa367305156b small fixes
cin
parents: 1
diff changeset
382
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
383 void InvokeHandler(ResultHandlerInfo handler) {
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
384 if (m_error == null) {
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
385 try {
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
386 if (handler.resultHandler != null)
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
387 handler.resultHandler(m_result);
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
388 } catch { }
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
389 }
2
aa367305156b small fixes
cin
parents: 1
diff changeset
390
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
391 if (m_error != null) {
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
392 try {
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
393 if (handler.errorHandler != null)
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
394 handler.errorHandler(m_error);
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
395 } catch { }
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
396 }
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
397 }
2
aa367305156b small fixes
cin
parents: 1
diff changeset
398
aa367305156b small fixes
cin
parents: 1
diff changeset
399
9
cin
parents: 7
diff changeset
400
cin
parents: 7
diff changeset
401 public bool IsExclusive {
cin
parents: 7
diff changeset
402 get {
cin
parents: 7
diff changeset
403 lock (m_lock) {
cin
parents: 7
diff changeset
404 return m_childrenCount <= 1;
cin
parents: 7
diff changeset
405 }
cin
parents: 7
diff changeset
406 }
cin
parents: 7
diff changeset
407 }
cin
parents: 7
diff changeset
408
cin
parents: 7
diff changeset
409 public PromiseState State {
cin
parents: 7
diff changeset
410 get {
cin
parents: 7
diff changeset
411 lock (m_lock) {
cin
parents: 7
diff changeset
412 return m_state;
cin
parents: 7
diff changeset
413 }
cin
parents: 7
diff changeset
414 }
cin
parents: 7
diff changeset
415 }
cin
parents: 7
diff changeset
416
cin
parents: 7
diff changeset
417 public bool Cancel(bool dependencies) {
cin
parents: 7
diff changeset
418 bool result;
cin
parents: 7
diff changeset
419
cin
parents: 7
diff changeset
420 lock (m_lock) {
cin
parents: 7
diff changeset
421 if (m_state == PromiseState.Unresolved) {
cin
parents: 7
diff changeset
422 m_state = PromiseState.Cancelled;
cin
parents: 7
diff changeset
423 result = true;
cin
parents: 7
diff changeset
424 } else {
cin
parents: 7
diff changeset
425 result = false;
cin
parents: 7
diff changeset
426 }
cin
parents: 7
diff changeset
427 }
cin
parents: 7
diff changeset
428
cin
parents: 7
diff changeset
429 if (dependencies && m_parent != null && m_parent.IsExclusive) {
cin
parents: 7
diff changeset
430 // TODO syncronize IsExclusive, AddHandler, Cancel (maybe CancelExclusive)
cin
parents: 7
diff changeset
431 m_parent.Cancel(true);
cin
parents: 7
diff changeset
432 }
cin
parents: 7
diff changeset
433
cin
parents: 7
diff changeset
434 if (result) {
cin
parents: 7
diff changeset
435 // state has been changed to cancelled, new handlers can't be added
cin
parents: 7
diff changeset
436 foreach (var handler in m_cancelHandlers)
cin
parents: 7
diff changeset
437 handler();
cin
parents: 7
diff changeset
438 }
cin
parents: 7
diff changeset
439
cin
parents: 7
diff changeset
440 return result;
cin
parents: 7
diff changeset
441 }
6
dfa21d507bc5 *refactoring: Promise.Then now returns a new chained promise
cin
parents: 2
diff changeset
442 }
2
aa367305156b small fixes
cin
parents: 1
diff changeset
443 }