2

我刚开始学习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 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: 

代码:

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;
    }
4

1 回答 1

7

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);
}
于 2012-11-16T05:50:46.033 回答