收到错误 - System.InvalidOperationException未处理

问题描述 投票:2回答:1

我刚刚开始学习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;
    }
c# multithreading invalidoperationexception
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);
}
© www.soinside.com 2019 - 2024. All rights reserved.