2016-12-06 135 views
-1
void worker_DoWork(object sender, DoWorkEventArgs e) 
    { 
     Action act = (Action)(() => 
     { 
      Thread.Sleep(1000); 
      RRect r = new RRect(rnd.Next(100, 100), rnd.Next(100, 100), GetMousePosition(), PickBrush(), 1080); 
      this.mainGrid.Children.Add(r); 
     }); 

     while (true) 
     { 
      this.Dispatcher.BeginInvoke(act, DispatcherPriority.Input); 
     } 
    } 

与背景的工人,我想每隔一秒添加一个矩形到我的主网格。我必须使用this.Dispatcher.BeginInvoke,因为避免了锁定。我的问题是,Dispatcher.beginInvoke导致内存泄漏

this.Dispatcher.BeginInvoke(act, DispatcherPriority.Input); 

代码块引起一个严重的内存泄露。它出什么问题了?

编辑1:

当我删除

Thread.Sleep(1000);   
RRect r = new RRect(rnd.Next(100, 100), rnd.Next(100, 100), GetMousePosition(), PickBrush(), 1080);   
this.mainGrid.Children.Add(r); 

没有什么变化。

+1

这是什么方式导致内存泄漏?你会看到你的内存使用量正在增加,但这很正常,因为你将更多的项目添加到你的网格中,因为它们仍然可以访问,所以它们必须留在内存中。 – Kenneth

+0

@Kenneth我知道它是如何工作的,只要我删除上面的代码块,没有什么改变。 – FreeMan

+0

'while(true){anything}'是个坏主意。你想等到它被调用吗?使用'Invoke'。 'BeginInvoke'会很快填满queue = OOM。 – Sinatr

回答

2

此代码

while (true) 
{ 
    this.Dispatcher.BeginInvoke(act, DispatcherPriority.Input); 
} 

队列工作的无限量的调度程序做。 BeginInvoke不会等待act调用完成,它只会将它放在一些内部列表中并返回。基本上这样做永远会吃掉所有可用的内存。

请注意,这不是内存泄漏。它按预期工作,你只是过度使用它。

+0

谢谢你的解释。 – FreeMan