-
Notifications
You must be signed in to change notification settings - Fork 246
/
Copy pathbase_deferral.h
77 lines (63 loc) · 2.01 KB
/
base_deferral.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
WINRT_EXPORT namespace winrt
{
#ifdef WINRT_IMPL_COROUTINES
template<typename D>
struct deferrable_event_args
{
Windows::Foundation::Deferral GetDeferral()
{
slim_lock_guard const guard(m_lock);
if (m_handle)
{
// Cannot ask for deferral after the event handler returned.
throw hresult_illegal_method_call();
}
Windows::Foundation::Deferral deferral{ {static_cast<D&>(*this).get_strong(), &deferrable_event_args::one_deferral_completed } };
++m_outstanding_deferrals;
return deferral;
}
[[nodiscard]] Windows::Foundation::IAsyncAction wait_for_deferrals()
{
struct awaitable : impl::suspend_always
{
bool await_suspend(coroutine_handle handle)
{
return m_deferrable.await_suspend(handle);
}
deferrable_event_args& m_deferrable;
};
co_await awaitable{ {}, *this };
}
private:
using coroutine_handle = impl::coroutine_handle<>;
void one_deferral_completed()
{
coroutine_handle resume = nullptr;
{
slim_lock_guard const guard(m_lock);
if (m_outstanding_deferrals <= 0)
{
throw hresult_illegal_method_call();
}
if (--m_outstanding_deferrals == 0)
{
resume = m_handle;
}
}
if (resume)
{
impl::resume_background(resume);
}
}
bool await_suspend(coroutine_handle handle) noexcept
{
slim_lock_guard const guard(m_lock);
m_handle = handle;
return m_outstanding_deferrals > 0;
}
slim_mutex m_lock;
int32_t m_outstanding_deferrals = 0;
coroutine_handle m_handle = nullptr;
};
#endif
}