Kill a MessageBox

G

Guest

How can I kill or close a MessageBox that is shown in a thread that I later
abort? In the following code, the MessageBox will always stay open until
closed by the user, even when the other event terminates first and the main
WaitForData method returns!

static public void WaitForData()
{
WaitHandle[] w = new WaitHandle[] { new AutoResetEvent(false), new
AutoResetEvent(false) };
Thread t0 = new Thread(new ParameterizedThreadStart(LookForData));
Thread t1 = new Thread(new ParameterizedThreadStart(LookForUserOverride));
t0.Start(w[0]);
t1.Start(w[1]);

if (WaitHandle.WaitAny(w) == 0)
{
Console.WriteLine("Confirmed data received; proceeding.");
t1.Abort();
}
else
{
Console.WriteLine("User Cancelled Wait for data; proceeding.");
t0.Abort();
}
}

static void LookForUserOverride(Object finish)
{
MessageBox.Show("Continue without waiting for data?", "Waiting for
data", MessageBoxButtons.OK);
((AutoResetEvent)finish).Set();
}

static void LookForData(Object finish)
{
... // Don't return until we find data
((AutoResetEvent)finish).Set();
}
 
M

Marc Gravell

My advice? IMO, don't ever abort a thread unless there is absolutely no
other way of doing things; and even then, consider a separate
AppDomain, as this can (on indeterminate occasion) leave the system in
a *very* unstable state. This is a vey bad way to manage threads, and
sooner or later it will jump up and bite you hard; your current issue
is just a friendly warning nibble from the OS... take heed ;-p

You should just be communicating to the other thread that it isn't
needed (e.g. via some sync-locked variable or ManualResetEvent etc) and
let it close itself down. If the problem is the modal MessageBox.Show,
then perhaps replace this with your own form, so that you have more
control and can ask it nicely to close itself before gracefully ending
the thread by exiting the delegate cleanly.

Marc
 

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