Asynchronous Form.ShowDialog()

  • Thread starter Thread starter NanoWizard
  • Start date Start date
N

NanoWizard

Enclosed below is a class that contains one member item called _frm.
It is just a standard System.Windows.Forms.Form class defined elsewhere
(just disregard the definition of the object). My question is if I
want to start a System.Windows.Forms.Form via ShowDialog in another
thread what is the best way to do it?
Basically, I want to start a form, then continue executing elsewhere
and occasionally posting data to the form. I know you could do a
ShowDialog and then spawn off another thread inside of the Form class
to do your processing, but I do not want to do it that way. I
understand that I'll have to use Invoke to update the Controls on the
form from the different threads. I am just interested in knowing if
these two ways are the only way I can do it. Start1 and Start2 are the
two separate methods. Also could someone explain why I need to do an
Application.DoEvents(); in method number 1? If I don't _frm's dialog
hangs. Thanks.

using System;
using System.Threading;
using System.Windows.Forms;

namespace testns
{
public class MyClass
{
private Form _frm;

public MyClass()
{}

public void Start1( )
{
_frm = new Form( );
Thread th = new Thread( new ThreadStart(
ThreadFunc1 ) );
th.Start( );
while ( _frm.DialogResult !=
DialogResult.Cancel )
{
Application.DoEvents( ); // why is this necessary in this
function?
// do whatever work is needed
}
}

public void Start2( )
{
Thread th = new Thread( new ThreadStart(
ThreadFunc2 ) );
th.Start( );
while ( _frm.DialogResult !=
DialogResult.Cancel )
{
// do whatever work is needed
}
}

private void ThreadFunc1( )
{
if ( _frm != null )
{
_frm.ShowDialog( );
}
}

private void ThreadFunc2( )
{
_frm = new Form( );
_frm.ShowDialog( );
}
}
}
 
Application.DoEvents is needed because you are in a tight loop, meaning the
thread cannot process any UI events. Application.DoEvents allows your code to
interrupt the looping thread and process the Windows messages currently in
the message queue, giving the impression of responsiveness. Generally (if not
always), if you are using this method, you have badly designed code.

I would suggest http://www.yoda.arachsys.com/csharp/threads/ as a good
reference for mutlithreaded coding techniques.
 
Back
Top