我正在將一組〜300位圖保存在併發隊列中。我正在做這個over-tcp視頻流媒體節目。如果服務器速度變慢,我將接收到的位圖保存在此隊列中(緩衝)。我創建了一個單獨的項目來測試,但我遇到了一些問題。從隊列讀取和寫入
雖然寫入線程正在工作(寫入隊列),但圖片框顯示隊列中的圖像,但它似乎跳過了其中的很多圖像(就像它正在讀取剛添加到「列表」中的圖片)通過寫入線程而不是FIFO行爲)。當寫入線程完成圖片框時,雖然我從隊列中讀取的循環仍在工作(當圖片框阻止隊列不爲空時),但它仍會阻止。
下面的代碼:
Imports System
Imports System.Drawing
Imports System.IO
Imports System.Threading
Imports System.Collections.Concurrent
Public Class Form1
Dim writeth As New Thread(AddressOf write), readth As New Thread(AddressOf read)
Dim que As New ConcurrentQueue(Of Bitmap), finished As Boolean
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
'Start button
writeth.Start()
readth.Start()
End Sub
Sub draw(ByRef pic As Bitmap)
If PictureBox1.Image IsNot Nothing Then
PictureBox1.Image.Dispose()
PictureBox1.Image = Nothing
End If
PictureBox1.Image = pic
End Sub
Sub read()
Dim bit As Bitmap
While (Not finished Or Not que.IsEmpty)
If que.TryDequeue(bit) Then
draw(bit.Clone)
'Still working after the writing stopped
If finished Then Debug.Print("picture:" & que.Count)
Thread.Sleep(2000) 'Simulates the slow-down of the server
End If
End While
End Sub
Sub write()
Dim count As Integer = 0
Dim crop_bit As New Bitmap(320, 240), bit As Bitmap
Dim g As Graphics = Graphics.FromImage(crop_bit)
For Each fil As String In Directory.GetFiles(Application.StartupPath & "/pictures")
count += 1
Debug.Print(count)
bit = Image.FromFile(fil)
g.DrawImage(bit, 0, 0, 320, 240)
que.Enqueue(crop_bit)
bit.Dispose()
Next
finished = True
'At this point the picture box freezes but the reading loop still works
End Sub
End Class
沒有錯誤。我認爲隊列中可能有副本(因爲圖片框出現凍結)?我嘗試了整數相同的代碼,它完美地工作。有什麼問題?
您有可能得到未報告的異常。由於它看起來只有3個物體被丟棄,所以當你耗盡物體時,可能會出現可怕的通用GDI錯誤或其他一些錯誤 – Plutonix
你是什麼意思?我只處理圖片boc圖像和一個位圖(「位」)。你是指那些? –