Mercurial > pub > ImplabNet
comparison Implab/Promise.cs @ 75:4439140706d0 v2
major refactoring, added tasks support
| author | cin |
|---|---|
| date | Wed, 10 Sep 2014 11:17:37 +0400 |
| parents | c4140283575c |
| children | c761fc982e1d |
comparison
equal
deleted
inserted
replaced
| 74:c4140283575c | 75:4439140706d0 |
|---|---|
| 223 // сделано для возвращаемого типа void | 223 // сделано для возвращаемого типа void |
| 224 protected void InternalCancel() { | 224 protected void InternalCancel() { |
| 225 Cancel(); | 225 Cancel(); |
| 226 } | 226 } |
| 227 | 227 |
| 228 | |
| 229 public IPromise<T> Then(ResultHandler<T> success, ErrorHandler<T> error, Action cancel) { | |
| 230 if (success == null && error == null && cancel == null) | |
| 231 return this; | |
| 232 | |
| 233 var medium = new Promise<T>(this, true); | |
| 234 | |
| 235 AddHandler(success, error, cancel, medium); | |
| 236 | |
| 237 return medium; | |
| 238 } | |
| 239 | |
| 228 /// <summary> | 240 /// <summary> |
| 229 /// Adds new handlers to this promise. | 241 /// Adds new handlers to this promise. |
| 230 /// </summary> | 242 /// </summary> |
| 231 /// <param name="success">The handler of the successfully completed operation. | 243 /// <param name="success">The handler of the successfully completed operation. |
| 232 /// This handler will recieve an operation result as a parameter.</param> | 244 /// This handler will recieve an operation result as a parameter.</param> |
| 239 var medium = new Promise<T>(this, true); | 251 var medium = new Promise<T>(this, true); |
| 240 | 252 |
| 241 AddHandler(success, error, null, medium); | 253 AddHandler(success, error, null, medium); |
| 242 | 254 |
| 243 return medium; | 255 return medium; |
| 256 } | |
| 257 | |
| 258 public IPromise Then(Action success, ErrorHandler error, Action cancel) { | |
| 259 return Then( | |
| 260 x => success(), | |
| 261 e => { | |
| 262 error(e); | |
| 263 return default(T); | |
| 264 }, | |
| 265 cancel | |
| 266 ); | |
| 244 } | 267 } |
| 245 | 268 |
| 246 public IPromise Then(Action success, ErrorHandler error) { | 269 public IPromise Then(Action success, ErrorHandler error) { |
| 247 return Then( | 270 return Then( |
| 248 x => success(), | 271 x => success(), |
| 265 var medium = new Promise<T>(this, true); | 288 var medium = new Promise<T>(this, true); |
| 266 | 289 |
| 267 AddHandler(success, null, null, medium); | 290 AddHandler(success, null, null, medium); |
| 268 | 291 |
| 269 return medium; | 292 return medium; |
| 293 } | |
| 294 | |
| 295 public void Last(ResultHandler<T> success, ErrorHandler error, Action cancel) { | |
| 296 if (success == null && error == null && cancel == null) | |
| 297 return; | |
| 298 | |
| 299 ErrorHandler<T> errorHandler = null; | |
| 300 if (error != null) | |
| 301 errorHandler = err => { | |
| 302 error(err); | |
| 303 return default(T); | |
| 304 }; | |
| 305 AddHandler(success, errorHandler, cancel, null); | |
| 306 } | |
| 307 | |
| 308 public void Last(ResultHandler<T> success, ErrorHandler error) { | |
| 309 Last(success, error, null); | |
| 310 } | |
| 311 | |
| 312 public void Last(ResultHandler<T> success) { | |
| 313 Last(success, null, null); | |
| 314 } | |
| 315 | |
| 316 public void Last(Action success,ErrorHandler error, Action cancel) { | |
| 317 Last(x => success(), error, cancel); | |
| 318 } | |
| 319 | |
| 320 public void Last(Action success,ErrorHandler error) { | |
| 321 Last(x => success(), error, null); | |
| 322 } | |
| 323 | |
| 324 public void Last(Action success) { | |
| 325 Last(x => success(), null, null); | |
| 270 } | 326 } |
| 271 | 327 |
| 272 public IPromise Error(ErrorHandler error) { | 328 public IPromise Error(ErrorHandler error) { |
| 273 if (error == null) | 329 if (error == null) |
| 274 return this; | 330 return this; |
| 305 AddHandler(null, handler, null, medium); | 361 AddHandler(null, handler, null, medium); |
| 306 | 362 |
| 307 return medium; | 363 return medium; |
| 308 } | 364 } |
| 309 | 365 |
| 310 public IPromise<T> Anyway(Action handler) { | |
| 311 if (handler == null) | |
| 312 return this; | |
| 313 | |
| 314 var medium = new Promise<T>(this, true); | |
| 315 | |
| 316 AddHandler( | |
| 317 x => handler(), | |
| 318 e => { | |
| 319 handler(); | |
| 320 throw new TransientPromiseException(e); | |
| 321 }, | |
| 322 null, | |
| 323 medium | |
| 324 ); | |
| 325 | |
| 326 return medium; | |
| 327 } | |
| 328 | |
| 329 /// <summary> | 366 /// <summary> |
| 330 /// Позволяет преобразовать результат выполения операции к новому типу. | 367 /// Позволяет преобразовать результат выполения операции к новому типу. |
| 331 /// </summary> | 368 /// </summary> |
| 332 /// <typeparam name="TNew">Новый тип результата.</typeparam> | 369 /// <typeparam name="TNew">Новый тип результата.</typeparam> |
| 333 /// <param name="mapper">Преобразование результата к новому типу.</param> | 370 /// <param name="mapper">Преобразование результата к новому типу.</param> |
| 334 /// <param name="error">Обработчик ошибки. Данный обработчик получит | 371 /// <param name="error">Обработчик ошибки. Данный обработчик получит |
| 335 /// исключение возникшее при выполнении операции.</param> | 372 /// исключение возникшее при выполнении операции.</param> |
| 336 /// <returns>Новое обещание, которое будет выполнено при выполнении исходного обещания.</returns> | 373 /// <returns>Новое обещание, которое будет выполнено при выполнении исходного обещания.</returns> |
| 337 public IPromise<TNew> Map<TNew>(ResultMapper<T, TNew> mapper, ErrorHandler<T> error) { | 374 public IPromise<TNew> Then<TNew>(ResultMapper<T, TNew> mapper, ErrorHandler<T> error) { |
| 338 if (mapper == null) | 375 if (mapper == null) |
| 339 throw new ArgumentNullException("mapper"); | 376 throw new ArgumentNullException("mapper"); |
| 340 | 377 |
| 341 // создаем прицепленное обещание | 378 // создаем прицепленное обещание |
| 342 var chained = new Promise<TNew>(this, true); | 379 var chained = new Promise<TNew>(this, true); |
| 368 ); | 405 ); |
| 369 | 406 |
| 370 return chained; | 407 return chained; |
| 371 } | 408 } |
| 372 | 409 |
| 373 public IPromise<TNew> Map<TNew>(ResultMapper<T, TNew> mapper) { | 410 public IPromise<TNew> Then<TNew>(ResultMapper<T, TNew> mapper) { |
| 374 return Map(mapper, null); | 411 return Then(mapper, null); |
| 375 } | 412 } |
| 376 | 413 |
| 377 /// <summary> | 414 /// <summary> |
| 378 /// Сцепляет несколько аснхронных операций. Указанная асинхронная операция будет вызвана после | 415 /// Сцепляет несколько аснхронных операций. Указанная асинхронная операция будет вызвана после |
| 379 /// выполнения текущей, а результат текущей операции может быть использован для инициализации | 416 /// выполнения текущей, а результат текущей операции может быть использован для инициализации |
| 382 /// <typeparam name="TNew">Тип результата указанной асинхронной операции.</typeparam> | 419 /// <typeparam name="TNew">Тип результата указанной асинхронной операции.</typeparam> |
| 383 /// <param name="chained">Асинхронная операция, которая должна будет начаться после выполнения текущей.</param> | 420 /// <param name="chained">Асинхронная операция, которая должна будет начаться после выполнения текущей.</param> |
| 384 /// <param name="error">Обработчик ошибки. Данный обработчик получит | 421 /// <param name="error">Обработчик ошибки. Данный обработчик получит |
| 385 /// исключение возникшее при выполнении текуещй операции.</param> | 422 /// исключение возникшее при выполнении текуещй операции.</param> |
| 386 /// <returns>Новое обещание, которое будет выполнено по окончанию указанной аснхронной операции.</returns> | 423 /// <returns>Новое обещание, которое будет выполнено по окончанию указанной аснхронной операции.</returns> |
| 387 public IPromise<TNew> Chain<TNew>(ChainedOperation<T, TNew> chained, ErrorHandler<T> error) { | 424 public IPromise<TNew> Then<TNew>(ChainedOperation<T, TNew> chained, ErrorHandler<T> error) { |
| 388 | 425 |
| 389 // проблема в том, что на момент связывания еще не начата асинхронная операция, поэтому нужно | 426 // проблема в том, что на момент связывания еще не начата асинхронная операция, поэтому нужно |
| 390 // создать посредника, к которому будут подвызяваться следующие обработчики. | 427 // создать посредника, к которому будут подвызяваться следующие обработчики. |
| 391 // когда будет выполнена реальная асинхронная операция, она обратиться к посреднику, чтобы | 428 // когда будет выполнена реальная асинхронная операция, она обратиться к посреднику, чтобы |
| 392 // передать через него результаты работы. | 429 // передать через него результаты работы. |
| 440 ); | 477 ); |
| 441 | 478 |
| 442 return medium; | 479 return medium; |
| 443 } | 480 } |
| 444 | 481 |
| 445 public IPromise<TNew> Chain<TNew>(ChainedOperation<T, TNew> chained) { | 482 public IPromise<TNew> Then<TNew>(ChainedOperation<T, TNew> chained) { |
| 446 return Chain(chained, null); | 483 return Then(chained, null); |
| 447 } | 484 } |
| 448 | 485 |
| 449 public IPromise<T> Cancelled(Action handler) { | 486 public IPromise<T> Cancelled(Action handler) { |
| 450 var medium = new Promise<T>(this, true); | 487 var medium = new Promise<T>(this, true); |
| 451 AddHandler(null, null, handler, medium); | 488 AddHandler(null, null, handler, medium); |
| 476 /// Преобразует результат обещания к нужному типу | 513 /// Преобразует результат обещания к нужному типу |
| 477 /// </summary> | 514 /// </summary> |
| 478 /// <typeparam name="T2"></typeparam> | 515 /// <typeparam name="T2"></typeparam> |
| 479 /// <returns></returns> | 516 /// <returns></returns> |
| 480 public IPromise<T2> Cast<T2>() { | 517 public IPromise<T2> Cast<T2>() { |
| 481 return Map(x => (T2)(object)x, null); | 518 return Then(x => (T2)(object)x, null); |
| 482 } | 519 } |
| 483 | 520 |
| 484 /// <summary> | 521 /// <summary> |
| 485 /// Дожидается отложенного обещания и в случае успеха, возвращает | 522 /// Дожидается отложенного обещания и в случае успеха, возвращает |
| 486 /// его, результат, в противном случае бросает исключение. | 523 /// его, результат, в противном случае бросает исключение. |
| 502 /// </remarks> | 539 /// </remarks> |
| 503 /// <param name="timeout">Время ожидания</param> | 540 /// <param name="timeout">Время ожидания</param> |
| 504 /// <returns>Результат выполнения обещания</returns> | 541 /// <returns>Результат выполнения обещания</returns> |
| 505 public T Join(int timeout) { | 542 public T Join(int timeout) { |
| 506 var evt = new ManualResetEvent(false); | 543 var evt = new ManualResetEvent(false); |
| 507 Anyway(() => evt.Set()); | 544 Finally(() => evt.Set()); |
| 508 Cancelled(() => evt.Set()); | |
| 509 | 545 |
| 510 if (!evt.WaitOne(timeout, true)) | 546 if (!evt.WaitOne(timeout, true)) |
| 511 throw new TimeoutException(); | 547 throw new TimeoutException(); |
| 512 | 548 |
| 513 switch (m_state) { | 549 switch (m_state) { |
| 702 | 738 |
| 703 IPromise IPromise.Error(ErrorHandler error) { | 739 IPromise IPromise.Error(ErrorHandler error) { |
| 704 return Error(error); | 740 return Error(error); |
| 705 } | 741 } |
| 706 | 742 |
| 707 IPromise IPromise.Anyway(Action handler) { | |
| 708 return Anyway(handler); | |
| 709 } | |
| 710 | |
| 711 IPromise IPromise.Finally(Action handler) { | 743 IPromise IPromise.Finally(Action handler) { |
| 712 return Finally(handler); | 744 return Finally(handler); |
| 713 } | 745 } |
| 714 | 746 |
| 715 IPromise IPromise.Cancelled(Action handler) { | 747 IPromise IPromise.Cancelled(Action handler) { |
