I'm working on a WinForm application with .NET CF 2.0 and I have a background running thread that needs to notify the user about various events. The problem is that everytime I want to notify the user with a MessageBox about an event, the application exits once the messagebox is displayed...I get the following message in the output window: The thread 0x2eda2a2 has exited with code 0 (0x0).
However, if I display the message in a label of my form, everything works well...here is the code I use:
-
public void DisplayMessage(string message)
-
{
-
if (InvokeRequired)
-
{
-
DisplayMessageDelegate displayMessageDelegate = new DisplayMessageDelegate(DisplayMessage);
-
this.Invoke(displayMessageDelegate, new object[] { message });
-
}
-
else
-
{
-
this.labelStatus.Text = message; // Works well
-
MessageBox.Show(message, "Info", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); // Application exits when called
-
-
}
-
}
Thanks in advance!
alex
Mike GoldPosted Aug 2, 2007, 4:23 PM
I just tried it with your code and it seems to work fine. Here is the code I called in my Form to ensure it was being called from a separate thread. Could some other part of your program be causing an exit? I would turn on exception handling under Exceptions in the Debug Menu and check the CLR Exceptions :
private void Form1_Load(object sender, EventArgs e){
// TODO: This line of code loads data into the 'fPNWINDDataSet.Customers' table. You can move, or remove it, as needed.
Thread oMessage = new Thread(new ThreadStart(ShowMessage));
oMessage.Start();
} private void ShowMessage()
{
DisplayMessage("testing");
} private delegate void DisplayMessageDelegate(string msg); public void DisplayMessage(string message)
{
if (InvokeRequired){
DisplayMessageDelegate displayMessageDelegate = new DisplayMessageDelegate(DisplayMessage); this.Invoke(displayMessageDelegate, new object[] { message });}
else{
// this.labelStatus.Text = message; // Works well MessageBox.Show(message, "Info", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); // Application exits when called}
}
Mike GoldPosted Aug 2, 2007, 4:07 PM
AlexPosted Aug 2, 2007, 1:49 PM
My delegate used to call a different method, but I've seen in the "Safe, Simple Multithreading in Windows Form" tutorial [http://msdn2.microsoft.com/en-us/library/ms951089.aspx] that their delegate was invoking back the same method, which avoids creating 2 methods doing almost the same thing.
Thanks!
Mike GoldPosted Aug 2, 2007, 1:34 PM
try putting the method that you are delegating to in a separate method. Looks like you are invoking back to the same method you are in, which I suspect is dangerous.