Skip to content

Commit 51ec25c

Browse files
authored
Make winrt::event clearable (#1074)
1 parent b8dcbbf commit 51ec25c

File tree

3 files changed

+56
-2
lines changed

3 files changed

+56
-2
lines changed

strings/base_events.h

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -375,8 +375,8 @@ WINRT_EXPORT namespace winrt
375375
using delegate_type = Delegate;
376376

377377
event() = default;
378-
event(event<Delegate> const&) = delete;
379-
event<Delegate>& operator =(event<Delegate> const&) = delete;
378+
event(event const&) = delete;
379+
event& operator =(event const&) = delete;
380380

381381
explicit operator bool() const noexcept
382382
{
@@ -466,6 +466,24 @@ WINRT_EXPORT namespace winrt
466466
}
467467
}
468468

469+
void clear()
470+
{
471+
// Extends life of old targets array to release delegates outside of lock.
472+
delegate_array temp_targets;
473+
474+
{
475+
slim_lock_guard const change_guard(m_change);
476+
477+
if (!m_targets)
478+
{
479+
return;
480+
}
481+
482+
slim_lock_guard const swap_guard(m_swap);
483+
temp_targets = std::exchange(m_targets, nullptr);
484+
}
485+
}
486+
469487
template<typename...Arg>
470488
void operator()(Arg const&... args)
471489
{

test/test/event_clear.cpp

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
#include "pch.h"
2+
3+
using namespace winrt;
4+
using namespace Windows::Foundation;
5+
6+
//
7+
// Checks that clear removes all event handlers
8+
//
9+
10+
TEST_CASE("event_clear")
11+
{
12+
event<TypedEventHandler<int, int>> event;
13+
int counter{};
14+
15+
auto a = event.add([&](auto && ...)
16+
{
17+
counter += 1;
18+
});
19+
20+
auto b = event.add([&](auto && ...)
21+
{
22+
counter += 10;
23+
});
24+
25+
REQUIRE(counter == 0);
26+
event(0, 0);
27+
REQUIRE(counter == 11);
28+
29+
// Clear event
30+
event.clear();
31+
32+
counter = 0;
33+
event(0, 0);
34+
REQUIRE(counter == 0);
35+
}

test/test/test.vcxproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -336,6 +336,7 @@
336336
<ClCompile Include="delegates.cpp" />
337337
<ClCompile Include="disconnected.cpp" />
338338
<ClCompile Include="enum.cpp" />
339+
<ClCompile Include="event_clear.cpp" />
339340
<ClCompile Include="guid.cpp" />
340341
<ClCompile Include="hresult_class_not_registered.cpp" />
341342
<ClCompile Include="error_info.cpp" />

0 commit comments

Comments
 (0)