问题
I have just started to learn windows application development, and we have been given self learn project to develop one windows application. I am trying to create the application to send email. I have created a class MsgSender.cs
to handle that. When I call that class from main form I am getting the following error
System.InvalidOperationException was unhandled.
Error Message-->
Cross-thread operation not valid: Control 'pictureBox1' accessed from a thread other than the thread it was created on.`
The stacktrace is as follows:
System.InvalidOperationException was unhandled
Message=Cross-thread operation not valid: Control 'pictureBox1' accessed from a thread other than the thread it was created on.
Source=System.Windows.Forms
StackTrace:
at System.Windows.Forms.Control.get_Handle()
at System.Windows.Forms.Control.SetVisibleCore(Boolean value)
at System.Windows.Forms.Control.set_Visible(Boolean value)
at UltooApp.Form1.sendMethod() in D:\Ultoo Application\UltooApp\UltooApp\Form1.cs:line 32
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
Code:
private void btnSend_Click(object sender, EventArgs e)
{
pictureBox1.Visible = true;
count++;
lblMsgStatus.Visible = false;
getMsgDetails();
msg = txtMsg.Text;
Thread t = new Thread(new ThreadStart(sendMethod));
t.IsBackground = true;
t.Start();
}
void sendMethod()
{
string lblText = (String)MsgSender.sendSMS(to, msg, "hotmail", uname, pwd);
pictureBox1.Visible = false;
lblMsgStatus.Visible = true;
lblMsgStatus.Text = lblText + "\nFrom: " + uname + " To: " + cmbxNumber.SelectedItem + " " + count;
}
回答1:
You can access Form GUI controls in GUI thread
and you are trying to access outside GUI thread that is the reason for getting exception. You can use MethodInvoker to access controls in the GUI thread.
void sendMethod()
{
MethodInvoker mi = delegate{
string lblText = (String) MsgSender.sendSMS(to, msg, "hotmail", uname, pwd);
pictureBox1.Visible = false;
lblMsgStatus.Visible = true;
lblMsgStatus.Text =
lblText + "\nFrom: " + uname +
" To: " + cmbxNumber.SelectedItem + " " + count;
};
if(InvokeRequired)
this.Invoke(mi);
}
来源:https://stackoverflow.com/questions/13411194/getting-error-system-invalidoperationexception-was-unhandled