I'm saving a set of ~300 bitmaps in a concurrent queue. I'm doing this for an over-tcp video streaming program. If the server slows down I save the received bitmaps in this queue (buffering). I created a separate project to test this but I'm having some problems.
While the writing thread is working (writing to the queue) the picture box is showing the images from the queue but it seems that it skips many of them(it is like it's reading the picture just added in the "list" by the writing thread-not FIFO behaviour). When the writing thread finishes the picture box it blocks although the loop in which I read from the queue is still working (when the picture box blocks the queue is not empty).
Here's the code:
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
There's no error. I think there might be copies in the queue(because the picture box appears to freeze)? I tried the same code with integers and it works perfectly. What's the problem?