-1

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);
   }
}
4

1 回答 1

1

您需要在代码中处理 Bitmap 对象,因为它包含托管资源,线程函数应该是:

void ThreadFunc()
   {


     while (!exit_flag)
     {
        // This blocks until an item appears in the queue.
        using (Bitmap local_bitmap = q.Take())
        {

        // process local_bitmap
        }
     }
   }

GC 被设计为自动管理内存,但是当调度 GC 时,运行时会考虑分配了多少托管内存,而不是非托管内存使用情况。所以在这种情况下,您需要自己处理对象或调用 GC.AddMemoryPressure 来加速 GC。

于 2015-01-07T19:30:45.727 回答