updating a window from another thread

  • Thread starter Thread starter Ron James
  • Start date Start date
R

Ron James

I have a Form based dialog which kicks off a worker
thread. The form has a progress bar, and a Cancel
button. The Cancel button Aborts the thread, and when
exiting, the thread attempts to Show a hidden control on
the form. This does not work, and I'm pretty sure it's
because the Show method is being called from a different
thread. Closer inspection of the documentation for Form
and the various controls confirms this. (Static members
are threadsafe, but instance members are not).

The worker thread also updates the progress bar directly
on the Dialog, and athough this is working, I now believe
that I shouldn't be doing this. Am I correct?

In the C++ world, I would have posted a user message to
the form, but I can't find anything similar in .NET.

How can I update by Dialog from the worket thread in a
threadsafe manner.

Thanks
 
Ron James said:
I have a Form based dialog which kicks off a worker
thread. The form has a progress bar, and a Cancel
button. The Cancel button Aborts the thread, and when
exiting, the thread attempts to Show a hidden control on
the form. This does not work, and I'm pretty sure it's
because the Show method is being called from a different
thread. Closer inspection of the documentation for Form
and the various controls confirms this. (Static members
are threadsafe, but instance members are not).

The worker thread also updates the progress bar directly
on the Dialog, and athough this is working, I now believe
that I shouldn't be doing this. Am I correct?

In the C++ world, I would have posted a user message to
the form, but I can't find anything similar in .NET.

How can I update by Dialog from the worket thread in a
threadsafe manner.

You can use the Invoke() method that exists on every
Windows Form control.

You define a method in your form that does what you
want it to do, then define a delegate for that method
then call invoke on the form. Something like:

SomeForm someFrm = new SomeForm();
....

if( someFrm.InvokeRequired )
{
someFrm.Invoke( new DoSomethingDelegate(
SomeForm.DoSomething()), new objet[]{
param1, param2 } );
}
else
{
someFrm.DoSomething(param1, param2);
}

Please see these two articles for some more
information:

Safe, Simple Multithread in Windows Forms
http://tinyurl.com/29sd [MSDN]

Second Look at Multithreading in Windows Forms
http://tinyurl.com/k480 [MSDN]

-c
 
Back
Top