248
|
1 using System;
|
|
2 using System.Runtime.CompilerServices;
|
|
3 using System.Threading;
|
|
4 using Implab.Parallels;
|
|
5
|
|
6 namespace Implab
|
|
7 {
|
|
8 public struct PromiseAwaiter : INotifyCompletion {
|
|
9 class PromiseEvent : IResolvable {
|
|
10 IDispatcher m_dispatcher;
|
|
11
|
|
12 Action m_handler;
|
|
13
|
|
14 public PromiseEvent(Action handler, IDispatcher dispatcher) {
|
|
15 m_handler = handler;
|
|
16 m_dispatcher = dispatcher;
|
|
17 }
|
|
18
|
|
19 public void Resolve() {
|
|
20 m_dispatcher.Enqueue(m_handler);
|
|
21 }
|
|
22
|
|
23 public void Reject(Exception error) {
|
|
24 m_dispatcher.Enqueue(m_handler);
|
|
25 }
|
|
26 }
|
|
27
|
|
28 readonly IPromise m_promise;
|
|
29 readonly IDispatcher m_dispatcher;
|
|
30
|
|
31 public PromiseAwaiter(IPromise promise, IDispatcher dispatcher) {
|
|
32 m_promise = promise;
|
|
33 m_dispatcher = dispatcher;
|
|
34 }
|
|
35
|
|
36 public PromiseAwaiter(IPromise promise) {
|
|
37 m_promise = promise;
|
|
38 m_dispatcher = GetDispatcher();
|
|
39 }
|
|
40
|
|
41 public void OnCompleted (Action continuation) {
|
|
42 if (m_promise != null)
|
|
43 m_promise.Then(new PromiseEvent(continuation, GetDispatcher()));
|
|
44 }
|
|
45
|
|
46 public void GetResult() {
|
|
47 m_promise.Join();
|
|
48 }
|
|
49
|
|
50 static IDispatcher GetDispatcher() {
|
|
51 if(SynchronizationContext.Current == null)
|
|
52 return ThreadPoolDispatcher.Instance;
|
|
53 return new SyncContextDispatcher(SynchronizationContext.Current);
|
|
54 }
|
|
55
|
|
56 public bool IsCompleted {
|
|
57 get {
|
|
58 return m_promise.IsResolved;
|
|
59 }
|
|
60 }
|
|
61 }
|
|
62 } |