Problem with ShowDialog() call from Thread() & InvalidOperationException...

J

Joe Duchtel

Hello -

I inherited some legacy code that was written for .NET 1.1 and worked
just fine there. I converted it to use .NET 2.0 but there is one
issue that still startles me ...

' .NET 1.1 >

mMyDialog = New cMyDialog() ' Create instance of dialog
mMyDialogThread = New Thread(AddressOf startDialogThread)
mMyDialogThread.Start() ' Start thread to call blocking ShowDialog()
' Thread.Sleep(250)
doStuff("A")

Private Sub doStuff(ByVal aStuff As String)
mMyDialog.changeStuff(aStuff)
End Sub

Private Sub startDialogThread()
mMyDialog.ShowDialog()
End Sub

' cMyDialog

Friend Sub changeStuff(ByVal aStuff As String)
OutputTextBox.AppendText(aStuff) ' OutputTextBox = RichTextBox
End Sub

I understand that there are so many things wrong with this but it
would probably require a complete re-write to do it right. Here is
the one update I made for .NET 2.0 to fix the problem of the debugger
throwing a InvalidOperationException (http://msdn.microsoft.com/en-us/
library/ms171728(VS.80).aspx) for the cross-thread access ...

' .NET 2.0 >

Private Delegate Sub changeStuffDelegate(ByVal aStuff As String)

Friend Sub changeStuff(ByVal aStuff As String)
If InvokeRequired Then
BeginInvoke(New changeStuffDelegate(AddressOf changeStuff),
aStuff)
Else
OutputTextBox.AppendText(aStuff) ' OutputTextBox =
RichTextBox
End If
End Sub

So this works fine as long as I run it on fast(er) machine. When this
is run on an older/slower PC, I get the InvalidOperationException that
OutputTextBox is "accessed from a thread other than the thread it was
created on". The solution to this was adding a Thread.Sleep(250)
between the starting of the thread and the doStuff().

I tried to use the Delegate for the startDialogThread() but that
didn't change anything either.

My question is whether anybody has an idea why this is happening. Is
the ShowDialog() happening and doing something while I already access
the OutputTextBox via doStuff()? The StackTrace includes the
following ...

....
at System.Windows.Forms.Form.ShowDialog()
at cXYZ.startDialogThread()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()

I guess I have a "solution" but I would like to know if there is a
better way to solve this problem? Is there any way I can wait for
ShowDialog() to have the dialog up and running?

Thanks,
Joe
 

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