簡體   English   中英

BlockingCollection,比賽條件?

[英]BlockingCollection, race condition?

我已經使用BlockingCollection實現了Producer / Consumer模式,但是它似乎並沒有像我期望的那樣阻塞。

我有一個線程從網絡攝像頭接收幀並將其添加到BlockingCollection

private void video_NewFrame(object sender, NewFrameEventArgs eventArgs) {
    image = (Bitmap)eventArgs.Frame.Clone();
    queue.Add(image);
    if (NewFrame != null)
        NewFrame(this, new NewFrameEventArgs(image)); //invoke the event for display
}

在另一個線程中,我引用了集合,並使用

public void Run() {
    foreach (Bitmap bmp in queue.GetConsumingEnumerable()) {
        // process bitmap

但是,正如您在下面看到的那樣,它傾向於拋出InvalidOperationException,告訴我要提取的幀正在其他地方使用。

img http://i17.photobucket.com/albums/b52/orubap/2012-03-24_020858.png

它並不總是立即發生,但我注意到它僅在隊列為空或接近空時發生(即,消費者比生產者快),因此我猜測這與添加的第一個圖像或最后拍攝的圖像。 任何想法為什么會發生這種情況?

當將NewFrame傳遞給NewFrame事件處理程序時,執行video_NewFrame的線程正在使用該圖像。 由於這是與Run並發Run ,因此無法阻止兩個線程同時訪問image (這只會在NewFrame事件處理程序處理圖像時讓Run使圖像出NewFrame發生,這解釋了為什么只有在隊列為空或幾乎為空時才看到它。)

一種解決方法是將調用NewFrame queue.Add(image); 之前的 queue.Add(image); (在video_NewFrame )。 這樣可以確保Run在事件處理程序完成之前看不到它(假設事件處理程序未存儲對其的引用)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM