251
|
1 using System;
|
|
2 using System.Threading.Tasks;
|
|
3
|
|
4 namespace Implab {
|
|
5 public static class TaskHelpers {
|
|
6
|
|
7 public static async Task Then(this Task that, Action fulfilled, Action<Exception> rejected) {
|
|
8 Safe.ArgumentNotNull(that, nameof(that));
|
|
9 if (rejected != null) {
|
|
10 try {
|
|
11 await that;
|
|
12 } catch (Exception e) {
|
|
13 rejected(e);
|
|
14 return;
|
|
15 }
|
|
16 } else {
|
|
17 await that;
|
|
18 }
|
|
19
|
|
20 if (fulfilled != null)
|
|
21 fulfilled();
|
|
22 }
|
|
23
|
|
24 public static async Task Then(this Task that, Action fulfilled) {
|
|
25 Safe.ArgumentNotNull(that, nameof(that));
|
|
26 await that;
|
|
27 if (fulfilled != null)
|
|
28 fulfilled();
|
|
29 }
|
|
30
|
|
31 public static async Task Then(this Task that, Func<Task> fulfilled) {
|
|
32 Safe.ArgumentNotNull(that, nameof(that));
|
|
33 await that;
|
|
34 if (fulfilled != null)
|
|
35 await fulfilled();
|
|
36 }
|
|
37
|
|
38 public static async Task Finally(this Task that, Action handler) {
|
|
39 Safe.ArgumentNotNull(that, nameof(that));
|
|
40 try {
|
|
41 await that;
|
|
42 } finally {
|
|
43 if (handler != null)
|
|
44 handler();
|
|
45 }
|
|
46 }
|
|
47
|
|
48 public static async void Then(this Task that, IResolvable next) {
|
|
49 try {
|
|
50 await that;
|
|
51 } catch (Exception e) {
|
|
52 next.Reject(e);
|
|
53 return;
|
|
54 }
|
|
55 next.Resolve();
|
|
56 }
|
|
57
|
|
58 public static async void Then<T>(this Task<T> that, IResolvable<T> next) {
|
|
59 T result;
|
|
60 try {
|
|
61 result = await that;
|
|
62 } catch (Exception e) {
|
|
63 next.Reject(e);
|
|
64 return;
|
|
65 }
|
|
66 next.Resolve(result);
|
|
67 }
|
|
68
|
|
69 }
|
|
70 } |