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