Reputation: 1457
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);
}
}
with background worker, I want to add a rectangle to my main grid every one second. I have to use this.Dispatcher.BeginInvoke because of avoiding lock. My question is that
this.Dispatcher.BeginInvoke(act, DispatcherPriority.Input);
code block causes a huge memory leak. What's wrong with it?
EDIT 1 :
When I delete
Thread.Sleep(1000);
RRect r = new RRect(rnd.Next(100, 100), rnd.Next(100, 100), GetMousePosition(), PickBrush(), 1080);
this.mainGrid.Children.Add(r);
Nothing changes.
Upvotes: 0
Views: 1667
Reputation: 28050
This code
while (true)
{
this.Dispatcher.BeginInvoke(act, DispatcherPriority.Input);
}
queues an infinite amount of work for the dispatcher to do. BeginInvoke
will not wait for the act
call to be completed, it will just put it in some internal list and return. Doing this basically forever will eat up all available memory.
Please note that this is not a memory leak. It is working as intended, you are just using it excessively.
Upvotes: 3