Thread-safe MessageBox in Windows form

I've used TestEmailer.TestForm from A class for sending emails with attachments in C#. and got an InvalidOperationException that related to How to: Make Thread-Safe Calls to Windows Forms Controls. The following code is how to make event handler safe.

            private void OnMailSent()

            {

            SetStatusBar("Mail sent.");// statusBar.Text = "Mail sent.";

                  //MessageBox.Show(this, "The mail has been sent.", "Mail Sent", MessageBoxButtons.OK, MessageBoxIcon.Information);

            ShowMessageBox("The mail has been sent.", "Mail Sent", MessageBoxButtons.OK);

            }

        // This delegate enables asynchronous calls for setting the text property on a TextBox control.

        delegate void SetTextCallback(string text);

        // This delegate enables asynchronous calls for Show MessageBox.

        delegate void ShowMessageBoxCallback(string text, string caption, MessageBoxButtons buttons);

 

        private void SetStatusBar(string text)

        {

            // InvokeRequired required compares the thread ID of the calling thread to the thread ID of the creating thread.

            // If these threads are different, it returns true.

            if (this.statusBar.InvokeRequired)

            {

                SetTextCallback d = new SetTextCallback(SetStatusBar);

                this.Invoke(d, new object[] { text });

            }

            else

            {

                this.statusBar.Text = text;

            }

        }

        private void ShowMessageBox(string text, string caption, MessageBoxButtons buttons)

        {

            // InvokeRequired required compares the thread ID of the calling thread to the thread ID of the creating thread.

            // If these threads are different, it returns true.

            if (this.InvokeRequired)

            {

                ShowMessageBoxCallback d = new ShowMessageBoxCallback(ShowMessageBox);

                this.Invoke(d, new object[] { text, caption, buttons });

            }

            else

            {

                MessageBox.Show(this, text, caption, buttons, MessageBoxIcon.Information);

            }

        }

 If  your method has no parameters, you can use MethodInvoker Delegate as suggested in

 

posted @ Tuesday, July 4, 2006 11:04 AM
Print

Comments on this entry:

No comments posted yet.

Your comment:



(not displayed)

 
 
 
 
 

Live Comment Preview:

 
«October»
SunMonTueWedThuFriSat
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678