WPF 窗口卡死或者假死解决方案(MVVM模式)

原文: WPF 窗口卡死或者假死解决方案(MVVM模式)

问题描述

项目情况如下:程序业务:点击开始之后,从文件中获取数据,将数据显示到界面(按照某种可视化的形式)上,直到文件数据读完或者界面操作停止才会停止数据刷新。

程序能正常运行,但是,当程序开始之后,拖拽、缩放窗体(WPF默认的窗体样式),界面假死,鼠标失去响应,也不能回到任务栏…可以通过按"Win"键恢复,但是恢复之后,界面有可能已经失去正常工作能力了——数据刷新不正确,时序不对等等问题。

原因分析

通过使用VS自带的性能分析,可以看到:界面在刷新过程中CPU占用非常高(这个有可能是没有等待的While(true)死循环导致的),同时在执行界面赋值、操作UI元素时消耗的性能非常高(使用了传统的赋值方式和操作UI元素属性导致的,因为在WPF中能够操作UI元素的只有UI线程,这就导致了UI线程的工作负担非常繁重,以至于让界面假死或者不响应鼠标操作等)。那么如何解决这个问题呢?

WPF中早已提供了非常便捷的实现方式来解决实时对UI元素的刷新。它就是数据绑定。下面我简单说下,为什么数据绑定可以解决这类问题,以及它带来的好处。

  • 数据绑定时,我们只需要修改数据源,而不会对UI元素做任何操作,因此我们写的逻辑可以使用异步或者多线程实现,相比于传统的赋值、操作模式,大大减轻了UI线程工作量。
  • 编写业务逻辑时,只需要关心数据源,而不会去操作任何UI元素,UI元素的修改全权交给了UI线程,这样大大提升了对象操作的安全性。

解决方案

下面我就模拟上述问题来展示我的解决方法。

使用代码的方式实现数据绑定。

  • 定义数据结构和实现通知接口ViewModel(MVVM模式)

        /// <summary>
        /// 所有轨迹
        /// </summary>
        public class TracksViewModel : ObservableCollection<TrackViewModel>
        { }
    
        /// <summary>
        /// 轨迹视图模型(ViewModel)
        /// </summary>
        public class TrackViewModel : BaseViewModel
        {
    
            public TrackViewModel(int id)
            {
                this.Id = id;
            }
    
            public int Id { get; private set; }
    
            private SolidColorBrush trackBorderBrush;
    
            public SolidColorBrush TrackBorderBrush
            {
                get { return trackBorderBrush; }
                set { trackBorderBrush = value; RaisePropertyChanged(); }
            }
    
            private Visibility trackVisibility;
    
            public Visibility TrackVisibility
            {
                get { return trackVisibility; }
                set { trackVisibility = value; RaisePropertyChanged(); }
            }
    
    
            private double x;
    
            public double X
            {
                get { return x; }
                set { x = value; RaisePropertyChanged(); }
            }
    
            private double y;
    
            public double Y
            {
                get { return y; }
                set { y = value; RaisePropertyChanged(); }
            }
    
        }
    
        /// <summary>
        /// ViewModel模型基类(属性更改通知)
        /// </summary>
        public class BaseViewModel : INotifyPropertyChanged
        {
            /// <summary>
            /// 当任何子属性更改其值时激发的事件
            /// </summary>
            public event PropertyChangedEventHandler PropertyChanged = (sender, e) => { };
    
            /// <summary>
            /// 调用此函数以触发 <see cref="PropertyChanged"/> 事件
            /// </summary>
            /// <param name="name"></param>
            protected void RaisePropertyChanged([CallerMemberName] string properName = "")
            {
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(properName));
            }
    
        }
    
    
        
        
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
  • UI元素自定义View(MVVM模式)

        /// <summary>
        /// 轨迹元素(View)
        /// </summary>
        public class TrackElement : Border
        {
            /// <summary>
            /// 绑定的数据源
            /// </summary>
            public static TracksViewModel TracksSource = new TracksViewModel();
    
            public TrackElement(int id)
            {
                this.Id = id;
                TracksSource.Add(new TrackViewModel(id) { });
                TrackElements.Add(id, this);
            }
    
            public int Id { get; private set; }
    
            /// <summary>
            /// 设置绑定
            /// </summary>
            private void SetBindingByCode()
            {
                this.SetBinding(Border.BorderBrushProperty, new Binding("TrackBorderBrush") { Source = TrackElement.TracksSource[Id] });
                this.SetBinding(Border.VisibilityProperty, new Binding("TrackVisibility") { Source = TrackElement.TracksSource[Id] });
                this.SetBinding(Canvas.LeftProperty, new Binding("X") { Source = TrackElement.TracksSource[Id] });
                this.SetBinding(Canvas.TopProperty, new Binding("Y") { Source = TrackElement.TracksSource[Id] });
            }
    
            /// <summary>
            /// 定义10个轨迹
            /// </summary>
            public Dictionary<int, TrackElement> TrackElements = new Dictionary<int, TrackElement>();
    
        }
    
    
        
        
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
  • 服务获取的数据模型Model(MVVM模式)

     /// <summary>
        /// 轨迹数据结构(服务中获取的)
        /// </summary>
        public class TrackModel
        {
            public TrackModel(int id)
            {
                Id = id;
            }
            public int Id { get; private set; }
    
            public int Value { get; set; }
        }
    
    
        
        
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
  • 业务逻辑

    /// <summary>
        /// MainWindow.xaml 的交互逻辑
        /// </summary>
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
    
                // 初始化元素(数据绑定)
                InitializeTrackElement();
            }
    
            /// <summary>
            /// 刷新目标(多线程实现)
            /// </summary>
            private void FlashTrack()
            {
                // 开启一个或多个线程来做我们需要的事情
                Task.Run(() =>
                {
                    // 获取一个随机种子,模拟刷新界面
                    Random rand = new Random();
                    while (IsRunning)
                    {
                        // TODO 打开文件获取数据
                        var data = new List<TrackModel>(10);
                        for (int i = 0; i < TrackCount; i++)
                        {
                            data.Add(new TrackModel(i) { Value = rand.Next(20) });
                        }
    
                        // 刷新数据源
                        foreach (var item in data)
                        {
                            if (item.Value % 2 == 0)
                            {
                                int next = rand.Next(360);
                                double c = Math.Cos(next);
                                double s = Math.Sin(next);
    
                                TrackElement.TracksSource[item.Id].TrackVisibility = Visibility.Visible;
                                if (item.Value < 5)
                                {
    
                                    TrackElement.TracksSource[item.Id].TrackBorderBrush = Brushes.Pink;
                                    // 在第2-3个线内的
                                    TrackElement.TracksSource[item.Id].X = 195 + c * rand.Next(150, 200);
                                    TrackElement.TracksSource[item.Id].Y = 195 + s * rand.Next(150, 200);
                                }
                                else if (item.Value < 10)
                                {
    
                                    TrackElement.TracksSource[item.Id].TrackBorderBrush = Brushes.Blue;
                                    // 在第2-3个线内的
                                    TrackElement.TracksSource[item.Id].X = 195 + c * rand.Next(100, 150);
                                    TrackElement.TracksSource[item.Id].Y = 195 + s * rand.Next(100, 150);
                                }
    
                                else if (item.Value < 15)
                                {
                                    TrackElement.TracksSource[item.Id].TrackBorderBrush = Brushes.Lime;
    
                                    // 在第1-2条线内的
                                    TrackElement.TracksSource[item.Id].X = 195 + c * rand.Next(50, 100);
                                    TrackElement.TracksSource[item.Id].Y = 195 + s * rand.Next(50, 100);
                                }
                                else
                                {
                                    TrackElement.TracksSource[item.Id].TrackBorderBrush = Brushes.Red;
    
                                    // 在第1个线内的
                                    TrackElement.TracksSource[item.Id].X = 195 + c * rand.Next(50);
                                    TrackElement.TracksSource[item.Id].Y = 195 + s * rand.Next(50);
    
                                    // 前面是原点坐标,后面的50表示半径
                                    //TrackElement.TracksSource[item.Id].X = 195 + c * (50);
                                    //TrackElement.TracksSource[item.Id].Y = 195 + s * (50);
                                }
                            }
                            else
                            {
                                TrackElement.TracksSource[item.Id].TrackVisibility = Visibility.Hidden;
                            }
                        }
    
                        // 防止 CPU 占用
                        Thread.Sleep(30);
                    }
                });
            }
    
            /// <summary>
            /// 当前是否正在刷新
            /// </summary>
            bool IsRunning = false;
    
            /// <summary>
            /// 初始化UI元素
            /// </summary>
            private void InitializeTrackElement()
            {
                for (int i = 0; i < TrackCount; i++)
                {
                    var track = new TrackElement(i)
                    {
                        BorderThickness = new Thickness(2),
                        Width = 10,
                        Height = 10,
                        CornerRadius = new CornerRadius(5),
                        Background = Brushes.Transparent,
    
                    };
    
                    ElementSpace.Children.Add(track);
                }
            }
    
            /// <summary>
            /// 目标数量
            /// </summary>
            private static int TrackCount = 100;
    
            /// <summary>
            /// 控制
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void Button_Click(object sender, RoutedEventArgs e)
            {
                if ((sender as Button).Content.ToString() == "Start")
                {
                    if (IsRunning) return;
    
                    IsRunning = true;
                    FlashTrack();
                }
                else
                {
                    IsRunning = false;
                }
            }
        }
    
        
        
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
  • XAML界面设计

    <Window x:Class="Melphi.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:local="clr-namespace:Melphi"
            mc:Ignorable="d"
            Title="MainWindow" Height="450" Width="800" Background="Black">
        <Grid>
    
            <Ellipse  Width="400" Height="400" >
                <Ellipse.Fill>
                    <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                        <GradientStop Color="#FF420404" Offset="0"/>
                        <GradientStop Color="#FF250332" Offset="1"/>
                    </LinearGradientBrush>
                </Ellipse.Fill>
            </Ellipse>
    
            <Ellipse  Width="300" Height="300" Stroke="#FFECECEC" StrokeThickness="1"/>
            <Ellipse  Width="200" Height="200" Stroke="#FFECECEC" StrokeThickness="1"/>
            <Ellipse  Width="100" Height="100" Stroke="#FFECECEC" StrokeThickness="1"/>
            <Ellipse  Width="20" Height="20" Fill="#FFECECEC" />
    
            <Canvas Width="400" Height="400" x:Name="ElementSpace" ClipToBounds="True"/>
    
            <StackPanel HorizontalAlignment="Right" VerticalAlignment="Center">
                <Button  Width="100" Content="Start" Click="Button_Click"/>
                <Button  Width="100" Content="Stop" Click="Button_Click"/>
            </StackPanel >
    
        </Grid>
    </Window>
    
    
        
        
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34

效果演示

在这里插入图片描述

总结

既然使用到了WPF,那么数据绑定是不得不学的一课,而且要非常认真的学习,因为它将影响你在这个平台上走多远。数据绑定可以概括为: 当数据源的属性值发生变化时,会主动通知UI元素展示最新的数据;同时,用户对控件的操作(修改)会直接修改数据源。这种编程方式也被称为数据驱动

Visual Studio是一个非常强大的IDE,我们要学着使用VS提供的功能来帮助我们分析我们程序的性能。从而找到问题,解决问题。


Over

每次记录一小步…点点滴滴人生路…

猜你喜欢

转载自www.cnblogs.com/lonelyxmas/p/12154723.html
今日推荐