我正在将一组〜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图像和一个位图(“位”)。你是指那些? –