我刚刚开始学习Windows应用程序开发,我们已经获得了自学项目来开发一个Windows应用程序。我正在尝试创建应用程序以发送电子邮件。我创建了一个类MsgSender.cs
来处理这个问题。当我从主窗体调用该类时,出现以下错误
System.InvalidOperationException 未处理。
错误消息 ->
跨线程操作无效:控制从创建它的线程以外的线程访问的"pictureBox1"。
堆栈跟踪如下所示:
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 ApplicationUltooAppUltooAppForm1.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:
法典:
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;
}
You can access Form GUI controls in GUI thread
并且您正在尝试访问外部GUI线程,这是获得异常的原因。您可以使用 MethodInvoker 来访问 GUI 线程中的控件。
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);
}