BlockingCollection 内存不足异常

BlockingCollection Out of Memory Exception

我有一个程序,我从相机中获取位图图像并将它们加载到 在线程中阻塞收集和处理。我正在从 UI 线程调用 SetImage。 它工作了几秒钟然后我遇到内存不足异常。请指教

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

您需要在代码中处理 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。