Threading and Forms

T

Tyson Ackland

I have written a very simple threading proggie in an attempt to teach myself
threading. I have seen it referred to in articles that Forms are not thread
safe. My form has two labels which are written to by different threads in
my example. It works fine so I'm wondering if anyone can tell me what I
need to watch out for with respect to Forms and threading? For what it's
worth, here is my short proggie:

Private Sub SomeTask()
' This thread simply counts upwards, displaying the count in the
label.
Dim i As Integer
For i = 1 To 100000
Me.Label2.Text = CInt(i / 100)
Application.DoEvents()
Next i
End Sub

Private Sub SomeOtherTask()
' This thread simply counts downwards, displaying the count in the
second label.
Dim i As Integer
For i = 100000 To 1 Step -1
Me.Label3.Text = CInt(i / 100)
Application.DoEvents()
Next i
End Sub

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Dim Thread1 As New System.Threading.Thread(AddressOf SomeTask)
Thread1.Start()
Dim Thread2 As New System.Threading.Thread(AddressOf SomeOtherTask)
Thread2.Start()
End Sub
 
A

AlexS

Hi, Tyson

to see conflicts and problems related to thread safety you have to run at
least 2 threads accessing same control. Or while thread is running you have
to touch control from main UI thread.
Documentation says that any instance methods are not guaranteed to be
thread-safe. Which means you might have no issues in some simple cases.

HTH
Alex
 
C

Cor Ligthert

Hi Tyson,

I have no answer on your question for you, however a greath simple sample of
multithreading, gives direct a good idea and I never thought on this sample.

(You have to change this but that is only a detail)
Me.Label3.Text = (i / 100).ToString

Cor
 

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