I have a program in which i am getting bitmap images from Camera loading them in blocking collection and processing in a thread. I am calling SetImage from UI thread. It works for few seconds then i run into out of memory exception. Please advise
Class MyThread
{
BlockingCollection<Bitmap> q = new BlockingCollection<Bitmap>();
Thread thread;
public MyThread()
{
thread = new Thread(ThreadFunc);
thread.Start();
}
void ThreadFunc()
{
Bitmap local_bitmap = null;
while (!exit_flag)
{
// This blocks until an item appears in the queue.
local_bitmap = q.Take();
// process local_bitmap
}
}
public void SetImage(Bitmap bm)
{
q.Add(bm);
}
}
You need to dispose the Bitmap object in your code as it contains managed resources, the thread func should be:
void ThreadFunc()
{
while (!exit_flag)
{
// This blocks until an item appears in the queue.
using (Bitmap local_bitmap = q.Take())
{
// process local_bitmap
}
}
}
GC is designed to manage memory automatically, but as when to schedule GC, the runtime takes into account how much managed memory is allocated, not the unmanaged memory usage. So in this case, you need dispose the object by your self or call GC.AddMemoryPressure to speeding the GC.