Simple WPF sample causes uncontrolled memory growth

后端 未结 4 761
天命终不由人
天命终不由人 2021-02-02 16:49

I have boiled down an issue I\'m seeing in one of my applications to an incredibly simple reproduction sample. I need to know if there\'s something amiss or something I\'m missi

4条回答
  •  借酒劲吻你
    2021-02-02 17:35

    Edit 2: Obviously not the answer, but was part of the back-and-forth among answers and comments here, so I'm not deleting it.

    The GC never gets a chance to collect those objects because your loop and its blocking calls never end, and therefore the message pump and events never get their turn. If you used a Timer of some sort so that messages and events actually have a chance to process, you probably wouldn't be able to eat up all your memory.

    Edit: The following does not eat up my memory as long as the interval is greater than zero. Even if the interval is just 1 Tick, as long as it isn't 0. If it's 0, we're back to the infinite loop.

    public partial class Window1 : Window {
        Class1 c;
        DispatcherTimer t;
        int count = 0;
        public Window1() {
            InitializeComponent();
    
            t = new DispatcherTimer();
            t.Interval = TimeSpan.FromMilliseconds( 1 );
            t.Tick += new EventHandler( t_Tick );
            t.Start();
        }
    
        void t_Tick( object sender, EventArgs e ) {
            count++;
            BuildCanvas();
        }
    
        private static void BuildCanvas() {
            Canvas c = new Canvas();
    
            Line line = new Line();
            line.X1 = 1;
            line.Y1 = 1;
            line.X2 = 100;
            line.Y2 = 100;
            line.Width = 100;
            c.Children.Add( line );
    
            c.Measure( new Size( 300, 300 ) );
            c.Arrange( new Rect( 0, 0, 300, 300 ) );
        }
    }
    

提交回复
热议问题