views:

563

answers:

4

I am creating a little testing component and am running into a problem

Basically the component is a decorator on a class that controls all access to the database, it creates a form with a two buttons on it: "Simulate Lost Connection" and "Reconnect". Press the button, and instead of letting function calls pass through the wrapper starts throwing NoConnectionException()s nice and simple, and real helpful for testing.

The problem is that this particular application when it detects a lost connection raises a modal dialog box "connection lost!" that sits there until the connection is regained. Because it is modal I cannot press my nifty button to simulate regained connectivity.

What I need to do therefore is to run my little testing form in a different thread. I'm not absolutely sure how to do that. I tried

new Thread(
  new ThreadStart(
    (Action)delegate {_form.Start();}
  )
).Start();

But the thread closes as soon as the method returns so the form never shows up except for an instant.

Any idea how I go about achieving what I want?

A: 

It sounds like you aren't holding on to your thread. It's an object, like everything else, so if it is scoped to your method, it will fall out of scope once your method exits. Try making it an instance variable.

Cory Foy
sorry, but that doesn't work. The thread is only going to stay open as long as there is code executing within it and Show() returns immediately
George Mauer
+2  A: 

You will need to start a message loop on the newly created thread. You can do that by calling Application.Run(form).

Stefan Schultze
Does this have any additional side-effects? In my particular case I only ever quit the application with an explicit call to Environment.Exit() so its ok, but what about in a more traditional application where the main UI thread exiting should end the app?
George Mauer
The application will run as long as one or more threads (and therefore message loops) are running. Exception: You mark the second thread as background thread (IsBackground = true). Then it will automatically end when the main UI thread is ended.
Stefan Schultze
+1  A: 

Try

new Thread(
  new ThreadStart((Action)delegate {
        _form.Start();
        System.Windows.Forms.Application.Run();
    }
  )
).Start();
lubos hasko
you mean _form.Show() I assume
George Mauer
your example has _form.Start() method. Anyway, the point was having message loop on that thread. Also look into Application.ExitThread() and Application.Exit() methods to control how your application will terminate, so it won't stay loaded in memory after closing UI.
lubos hasko
A: 

in fact there is the solution : use showdialog : System.Threading.Thread t = new System.Threading.Thread(new form1().ShowDialog()); t.Start();

noel