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

Point 1:检查Static事件

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

例全局事件:
    public class WQEvents
    {
        public static event DelegateMethod<SettingEventArgs> 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)
        {
            // 监听主窗口鼠标移动事件
        }
    }
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值