您当前的位置: 首页 >  性能优化

君子居易

暂无认证

  • 0浏览

    0关注

    210博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

避坑OutOfMemory - WPF程序性能优化一

君子居易 发布时间:2021-03-17 11:00:16 ,浏览量:0

Point 1:检查Static事件

UserControl或Page中引用了全局事件,不再使用时,需要立即释放掉。

例全局事件:     public class WQEvents     {         public static event DelegateMethod OnSettingChanged;

        public static void DoSettingChanged(SettingEventArgs args)         {             if (OnSettingChanged != null && args != null)                 OnSettingChanged(args);         }     }

调用时,比较好的习惯:         private void UserControl_Unloaded(object sender, RoutedEventArgs e)         {             WQEvents.OnSettingChanged -= WQEvents_OnSettingChanged;         }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)         {             WQEvents.OnSettingChanged -= WQEvents_OnSettingChanged; // 避免多次附加事件             WQEvents.OnSettingChanged += WQEvents_OnSettingChanged;         }

Point2:合理使用资源

假若需要用图片作为背景图,不推荐直接在Xaml中用Image作为背景底图,尤其该背景需要重复使用时,推荐使用ImageBrush。

例:https://github.com/DuelWithSelf/WPFEffects 同样的效果,一个内存增加7M, 一个增加了90M。

Point3:良好的Timer使用习惯 

在使用Timer之前,养成习惯先写好两个方法:Create,Free.  页面Unloaded时,无论不在需要了还是暂时卸载,只要不需要继续在后台处理事务,均应该Free掉Timer 或Stop掉Timer。

页面内容卸载时,确保Timer被释放。

Point4:及时释放引用 

如上图,CompositionTarget.Rendering 事件, 检查所有  " += "; 对于Static Event, Timer.Tick或者Rendering等,要有始有终, “-=” 是非常必要的。

Point5:Window对象的使用

示例及说明如下: public partial class ImagePerformanceModuleView : UserControl     {         private MainWindow MainWnd;

        public ImagePerformanceModuleView()         {             InitializeComponent();

            this.Loaded += ImagePerformanceModuleView_Loaded;             this.Unloaded += ImagePerformanceModuleView_Unloaded;         }

        private void ImagePerformanceModuleView_Loaded(object sender, RoutedEventArgs e)         {             MainWnd = Application.Current.MainWindow as MainWindow;             if (MainWnd != null)             {                 MainWnd.MouseMove += MainWnd_MouseMove;                 MainWnd.MouseUp += MainWnd_MouseUp;             }         }

        private void ImagePerformanceModuleView_Unloaded(object sender, RoutedEventArgs e)         {             // 界面Unloaded时,一定要及时释放掉对主窗口的引用             if(MainWnd != null)             {                 MainWnd.MouseMove -= MainWnd_MouseMove;                 MainWnd.MouseUp -= MainWnd_MouseUp;                 MainWnd = null;             }         }

        private void MainWnd_MouseUp(object sender, MouseButtonEventArgs e)         {             // 监听主窗口鼠标抬起事件         }

        private void MainWnd_MouseMove(object sender, MouseEventArgs e)         {             // 监听主窗口鼠标移动事件         }     }  

关注
打赏
1660814979
查看更多评论
立即登录/注册

微信扫码登录

0.1458s