2015-01-07 91 views
-1

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

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

使用搜索,配置位图。 – CodeCaster

+0

除了忘记处置位图之外,当相机以比处理它们更快的速度拍摄位图时,您将始终得到此异常。这是一个非常可能的事故。 BlockingCollection的要点是当它变满时让它阻塞。使用带* int *的构造函数。 –

+0

感谢@HansPassant的输入。对我而言,情况正是如此,我的相机比我能处理它们的速度更快。你是否建议我使用有限集合? – Zshan

回答

1

您需要处理位图对象在你的代码,因为它包含了管理资源,线程FUNC应该是:

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。