Reputation: 181
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??
Upvotes: 3
Views: 3936
Reputation: 32681
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);
Upvotes: 3