Asynchronous painting in control using BeginInvoke in Invalidate/Refresh

J

John Bonds

I have a control that paints an System.Drawing.Bitmap. Let's say that I fork
off 5 worker threads to do some image processing and I want to display each
image that the worker threads process in my control. So I will basically
have a bunch of threads throwing images to my control which is then
displaying them. The articles I've read seem to indicate that really only
the painting of the control needs to be handled in the main UI thread and
that everything else up to that point can be done in the worker thread. So I
overloaded the Invalidate method as follows:

Private Overloads Sub Invalidate()
If Me.InvokeRequired Then
Me.BeginInvoke(New MethodInvoker(AddressOf MyBase.Invalidate))
Else
MyBase.Invalidate()
End If
End Sub

Since I'm painting a System.Drawing.Bitmap, I also need to make sure that
only one thread (including the UI thread) accesses the bitmap at a time. For
this, I do a little SyncLock-ing as follows:

'Called to display a new image
Public Sub DisplayImage(ByVal vBitmap As System.Drawing.Bitmap)
SyncLock mBitmapSyncLock
If Not mCurrentDisplayImage Is Nothing Then
mCurrentDisplayImage.Dispose()
mCurrentDisplayImage = vBitmap
End SyncLock
Invalidate()
End Sub

'Paint the bitmap
Protected Overrides Sub OnPaint(ByVal e As
System.Windows.Forms.PaintEventArgs)
SyncLock mBitmapSyncLock
'Painting goes on here
End SyncLock
End Sub

My question is: will this work? I've had problems in the past of my app.
vanishing on me and displaying errors such as "Failed to load resources from
Setup File" or something and I believe it was from violating some rule of
the updating the UI from a different thread. Does the above look thread
safe? Can I call the DisplayImage(...) method and be sure that everything is
being handled in the proper thread?

Thanks
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top