Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backgroundworker memory leak and the "using" statement

We have a program (Form) which uses many backgroundworker threads in many occasions (we cannot reuse them).

We noticed that the memory of the program keeps growing and analyzing this with a memory profiler I've noticed that there are many backgroundworker objects.

I thought that if I use the "using" statement will do the trick and dispose the objects but it doesn't seem to work.

using (BackgroundWorker bgwConnectClient = new BackgroundWorker())
{
    bgwConnectClient.DoWork += new DoWorkEventHandler(bgwConnectClient_DoWork);
    bgwConnectClient.RunWorkerAsync();
}

Any idea??

like image 230
Dafna Avatar asked Nov 19 '25 16:11

Dafna


1 Answers

You are having memory leak because your object is hooked to an event. you need to alter your code

BackgroundWorker bgwConnectClient = new BackgroundWorker();
bgwConnectClient.DoWork += new DoWorkEventHandler(bgwConnectClient_DoWork);
bgwConnectClient.RunWorkerAsync();

after you have completed the work and bgwConnect is no longer required

do this

bgwConnectClient.DoWork -= new DoWorkEventHandler(bgwConnectClient_DoWork);
like image 127
Ehsan Avatar answered Nov 22 '25 05:11

Ehsan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!