我应该为UserControl实现IDispose

时间:2014-11-05 13:17:56

标签: c# xaml windows-phone-8 user-controls

我写了一个usercontrol,向我的页面显示Google Admod。这个控件很简单,只有1个网格(LayoutRoot),1个图像(从我的数据库中随机获取),以显示何时无法获得广告。在每个页面上我都有此控件,我请求新广告并添加到此LayoutRoot。问题是,重复创建此用户控件(当页面之间的导航具有此控件时)导致内存泄漏(由于背景图像或谷歌浏览器,我不确定)。所以现在我想把这个控件实现给Idispose,但我仍然感到困惑:

  1. 我可以(并且我是否需要)为UserControl实现Idispose?
  2. 如果我这样做,我的页面会在页面完成后调用处理此控件吗?
  3. 实现IDispose的正确方法是什么?按照this我写了一个测试,但我不确定这是否正确?

    bool disposed = false;
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
    protected virtual void Dispose(bool disposing)
    {
        if (disposed)
            return;
    
        if (disposing)
        {
            // I'm don't know what to put here ?
        }
        adview.FailedToReceiveAd -= adview_FailedToReceiveAd;
        adview.ReceivedAd -= adview_ReceivedAd;
        adview = null;
        request = null;
        imgMyAd.Source = null;
        imgMyAd = null;
        disposed = true;
    }
    
    ~AdPro()
    {
        Dispose(false);
    }
    
  4. 这是我的UserControl:

    <UserControl>
        <Grid x:Name="LayoutRoot" Background="Black" Height="60">
            <Image x:Name="imgMyAd" Height="{Binding Height ,ElementName=LayoutRoot}"
                    Width="{Binding Width ,ElementName=LayoutRoot}" Stretch="Fill"/>            
            <Grid x:Name="AdMob">                          
            </Grid>
        </Grid>
    </UserControl>
    

    c#

    public partial class AdPro : UserControl
    {
        public AdPro()
        {            
            InitializeComponent();
            this.DataContext = App.AdControlD;
            imgMyAd.Source = GetRandomBGImg();     // get the image from my server
            if (App.IsNetworkAvailable)          // check if internet's available
            {                 
                AddAdtoGrid();                
            }
        }
    
        AdRequest request = null;
        AdView adview = null;
    
        public void AddAdtoGrid()
        {
            adview = new AdView()
            {                
                AdUnitID="xxxxxx‏",
                Format = AdFormats.Banner,
                VerticalAlignment = System.Windows.VerticalAlignment.Center,
                HorizontalAlignment = System.Windows.HorizontalAlignment.Center
            };
            AdMob.Children.Add(adview);
            request = new AdRequest();
            request.ForceTesting = true;
            adview.FailedToReceiveAd += adview_FailedToReceiveAd;
            adview.ReceivedAd += adview_ReceivedAd;
            adview.LoadAd(request);
        }
    
        void adview_ReceivedAd(object sender, AdEventArgs e)
        {
            Debug.WriteLine("get ad success");            
        }
    
        void adview_FailedToReceiveAd(object sender, AdErrorEventArgs e)
        {
            Debug.WriteLine("get ad failed: " + e.ErrorCode);
        }
    
    }
    

0 个答案:

没有答案