Expected Exception

H

Hayato Iriumi

It's a big taboo to manipulate Windows Form directly from another thread
and I did come across the issue in my actual development. My colleague and
I were talking about it this morning and we wanted to see if we could actually
get the exception to happen. So I did this sample in VB .NET.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button1.Click
Dim t As New Thread(AddressOf Me.MyThreadSub)
t.Start()
End Sub


Private Sub MyThreadSub()
Button1.Text = "Test"
End Sub

Somehow, error is not happening... Now I'm confused..
 
M

Michael D. Ober

The problem is that forms aren't thread safe from the standpoint of multiple
threads simultaneously writing to a form. You will generate the error much
faster if you create 10 threads and have them all randomly write to your
form. The way to handle this is to pass a message to the form and have it
do it's own update. The message can have as one of it's parameters the
address of the data payload being passed to the form.

Mike Ober.
 
H

Hayato Iriumi

Hello W.G. Ryan eMVP,

I've never tried so hard to get an exception to happen... but I suceeded
in it. :D I got the following exception.

An unhandled exception of type 'System.ArgumentException' occurred in system.windows.forms.dll
Additional information: Controls created on one thread cannot be parented
to a control on a different thread.

And this is what I did.


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button1.Click
For i As Integer = 0 To 10
Dim t As New Thread(AddressOf Me.MyThreadSub)
t.Start()
Next
End Sub


Private Sub MyThreadSub()
Dim t As New TextBox
Me.Controls.Add(t)
End Sub

I do remember now that that's exactly what I did in my actual development
and got stuck for a while because I didn't know about that concept. Anyway...
I successfully got an exception to happen! Now I'm happy!
 
H

Hayato Iriumi

Hello Rulin,

Yeah, if it's not thread safe, you expect exception, wouldn't you?
 

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