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 GoldRank #50 · 30.6K pointsPosted Aug 2, 2007, 9:34 AM EDT
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.
Alex3 pointsPosted Aug 2, 2007, 9:49 AM EDT
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 GoldRank #50 · 30.6K pointsPosted Aug 2, 2007, 12:07 PM EDT
Mike GoldRank #50 · 30.6K pointsPosted Aug 2, 2007, 12:23 PM EDT
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 wellMessageBox.Show(message, "Info", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); // Application exits when called
}
}