我需要取消订阅 Xamarin.Forms 中的 GestureRecogniser 吗?
Do I need to unsubscribe from a GestureRecogniser in Xamarin.Forms?
所以我有以下控件,扩展自 Label
public Hyperlink()
{
var tapGesture = new TapGestureRecognizer();
tapGesture.Tapped += TapGesture_Tapped;
this.GestureRecognizers.Add(tapGesture);
}
现在我的问题是,我需要解开GestureRecogniser
吗?
我对 GarbageCollection 的理解是因为 Hyperlink
对象负责 tapGesture
它应该能够处理它;但这是 Xamarin.Forms 的世界,任何事情都会发生。
所以我需要 Dispose
代码来避免潜在的内存泄漏并避免使对象保持活动状态
public void Dispose()
{
if (this.GestureRecognizers.Count > 0)
{
var tapGesture = this.GestureRecognizers[0] as TapGestureRecognizer;
tapGesture.Tapped -= TapGesture_Tapped;
this.GestureRecognizers.Clear();
}
}
This link, as well as this link 说我应该删除 GestureRecognisers
但没有详细说明为什么
除非您使用持久性页面,否则您不需要手动处理您的手势识别器。当任何使用它的页面被 GC 弹出和收集时,它都会被销毁。
如果你放心,你仍然可以手动处理它,它不会伤害任何东西,但不是必需的。
根据Cross-Platform Performance,建议您退订GestureRecogniser。
To prevent memory leaks, events should be unsubscribed from before the subscriber object is disposed of. Until the event is unsubscribed from, the delegate for the event in the publishing object has a reference to the delegate that encapsulates the subscriber's event handler. As long as the publishing object holds this reference, garbage collection will not reclaim the subscriber object memory.
所以我有以下控件,扩展自 Label
public Hyperlink()
{
var tapGesture = new TapGestureRecognizer();
tapGesture.Tapped += TapGesture_Tapped;
this.GestureRecognizers.Add(tapGesture);
}
现在我的问题是,我需要解开GestureRecogniser
吗?
我对 GarbageCollection 的理解是因为 Hyperlink
对象负责 tapGesture
它应该能够处理它;但这是 Xamarin.Forms 的世界,任何事情都会发生。
所以我需要 Dispose
代码来避免潜在的内存泄漏并避免使对象保持活动状态
public void Dispose()
{
if (this.GestureRecognizers.Count > 0)
{
var tapGesture = this.GestureRecognizers[0] as TapGestureRecognizer;
tapGesture.Tapped -= TapGesture_Tapped;
this.GestureRecognizers.Clear();
}
}
This link, as well as this link 说我应该删除 GestureRecognisers
但没有详细说明为什么
除非您使用持久性页面,否则您不需要手动处理您的手势识别器。当任何使用它的页面被 GC 弹出和收集时,它都会被销毁。
如果你放心,你仍然可以手动处理它,它不会伤害任何东西,但不是必需的。
根据Cross-Platform Performance,建议您退订GestureRecogniser。
To prevent memory leaks, events should be unsubscribed from before the subscriber object is disposed of. Until the event is unsubscribed from, the delegate for the event in the publishing object has a reference to the delegate that encapsulates the subscriber's event handler. As long as the publishing object holds this reference, garbage collection will not reclaim the subscriber object memory.