首页 > 解决方案 > 我是否需要取消订阅 Xamarin.Forms 中的 GestureRecogniser?

问题描述

所以我有以下控制,从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();
    }
}

这个链接这个链接都说我应该删除GestureRecognisers但没有详细说明原因

标签: c#xamarinxamarin.formsmemory-leaksgarbage-collection

解决方案


根据Cross-Platform Performance,建议您取消订阅 GestureRecogniser。

为防止内存泄漏,应在处理订阅者对象之前取消订阅事件。在取消订阅事件之前,发布对象中的事件委托具有对封装订阅者事件处理程序的委托的引用。只要发布对象持有这个引用,垃圾回收就不会回收订阅者对象的内存。


推荐阅读