Can I handle an event with a lambda in C++/CX?
Asked Answered
P

2

9

Is it possible to handle an event with a lambda in C++/CX? As an example, what would be the best way to convert this snippet of code from C# into C++/CX?

this.animation.Completed += (s, e) =>
{
   animation.Begin();
};
Portion answered 18/9, 2012 at 14:32 Comment(0)
G
6

Yes, that's the correct syntax. However, we recommend that you use a function handler instead of a lambda because a lambda can introduce a circular references and prevent memory from being freed.

http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh755799.aspx

In general, it's better to use a named function, rather than a lambda, for an event handler unless you take great care to avoid circular references. A named function captures the "this" pointer by weak reference, whereas a lambda captures it by strong reference and creates a circular reference. For more information, see Weak references and breaking cycles (C++/CX).

Gstring answered 9/10, 2012 at 20:22 Comment(0)
P
5

Here's what I ended up doing.

animation->Completed += ref new EventHandler<Object^>([this](Object^, Object^)
{
   animtion->Begin();
});
Portion answered 18/9, 2012 at 14:52 Comment(3)
If I understood ThomasP above wouldn't that capture this by strong ref and thus create a circular reference creating a potential memory leak. msdn.microsoft.com/en-US/library/windows/apps/hh699859.aspx seems to imply you should capture this using WeakReference?Ornate
It's unfortunate that events use strong reference. When would I want an event to keep an object alive? That's one of my few complaints of C#.Portion
I am of the same opinion and I suspect that's why they introduced IWeakEventListener in WPF. It's clunk though. (they should also made null values unsafe IMHO)Ornate

© 2022 - 2024 — McMap. All rights reserved.