简体   繁体   English

每次使用FindViewById之后,我应该调用Dispose()吗?

[英]Should I be calling Dispose() after every usage of FindViewById

To prevent any memory leaks in Android Xamarin, should I be calling Dispose() after usage of FindViewById? 为防止Android Xamarin中发生任何内存泄漏,使用FindViewById后是否应该调用Dispose()?

An example: 一个例子:

void SetTextSomewhereInMyView()
{
var myTextView = FindViewById<TextView>(Resouce.Id.myTextView);
myTextView.Text = "This is my Text View";

// Should I be calling dispose now? or is it OK not to call dispose?
myTextView.Dispose(); // ?
}

I haven't seen Dispose being called that much in Xamarin examples but then I read on a few places that this would be a good practise. 在Xamarin示例中,我还没有看到Dispose被这么称呼,但是后来我在几个地方读到,这将是一个很好的实践。 What would be the final word on this? 最后的话是什么?

FindViewById is an expensive call you should not do that often. FindViewById是一个昂贵的调用,您不应该经常这样做。 Instead save the reference at an field and dispose that instance at OnDestroy or OnTrimMemory. 而是将引用保存在字段中,然后将该实例放置在OnDestroy或OnTrimMemory上。

If you need this view only once then dispose it right after usage. 如果仅需要一次此视图,则在使用后立即将其处置。

I think it would be more expensive to call FindViewById every time you need it than the overhead of not calling Dispose . 我认为每次需要时都调用FindViewById比不调用Dispose的开销要昂贵。 My method would be lazy load my views like this: 我的方法将像这样延迟加载我的视图:

private TextView _myTextView;
public TextView MyTextView
{
    get
    {
       return _myTextView?? (_myTextView= FindViewById<TextView>(Resouce.Id.myTextView));
    }
}

void SetTextSomewhereInMyView()
{
   MyTextView.Text = "This is my Text View";

}

Therefore FindViewById is only called when needed and the reference to the view is then cached for later. 因此,仅在需要时才调用FindViewById然后将对视图的引用进行缓存以备后用。

In Short: 简而言之:

If you would like to use the TextView again you and you have Disposed of it would have to call FindViewById Which is an expensive operation. 如果您想再次使用TextView ,并且您已经对其进行了Disposed ,则必须调用FindViewById这是一项昂贵的操作。 However if you are setting a TextView's Text value with no intention of ever needing a reference to that TextView again it is good practice to call Dispose 但是,如果您要设置TextView's TextTextView's Text不想再次引用该TextView,则最好调用Dispose

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM