I have a C# WinForms application where pressing a button instantiates an object, subscribes to its events, then launches a thread based on a method of that object. The object's method uses a lot of memory, but once the thread is finished, I would think it should be released when GC.Collect()
is called. However, this does not seem to be the case. This program can use up to gigabytes of memory so this is not a small concern, and it only seems to be released upon closing the program or pressing the button again.
Here is a sample app that demonstrates the problem:
using System;
using System.Threading;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private Worker worker;
private void button1_Click(object sender, EventArgs e)
{
worker = new Worker();
worker.Finished += worker_Finished;
Thread thread = new Thread(new ThreadStart(worker.DoWork));
thread.IsBackground = true;
thread.Start();
}
void worker_Finished(object sender, EventArgs e)
{
worker.Finished -= worker_Finished;
GC.Collect();
MessageBox.Show((Environment.WorkingSet / 1024 / 1024).ToString() + " MB in use");
}
}
public class Worker
{
public event EventHandler Finished;
protected virtual void OnFinished(EventArgs e)
{
EventHandler handler = Finished;
if(handler != null)
{
handler(this, e);
}
}
public void DoWork()
{
Random random = new Random();
string[] list = new string[10000000];
for(int i = 0; i < list.Length; i++)
{
list[i] = random.NextDouble().ToString();
}
//list = null;
OnFinished(new EventArgs());
}
}
}
Note that in this case, uncommenting the line list = null;
seems to resolve the issue, though I'm not sure why. In my actual application, I have tried setting all the big objects to null before the function ends but it doesn't seem to help. So it's not a perfect recreation of the problem but hopefully somebody can explain what is happening here which will help me solve the actual problem.
Also, I'm aware this question is very similar, but in my case I'm explicitly forcing a garbage collection.