2012-11-16 61 views
2

我刚开始学习windows应用程序开发,并且我们已经给自学项目开发​​了一个windows应用程序。我正在尝试创建应用程序以发送电子邮件。我创建了一个类MsgSender.cs来处理这个问题。当我从主窗体调用该类时,出现以下错误出现错误 - System.InvalidOperationException未处理

System.InvalidOperationException未处理。

错误消息 - >

跨线程操作无效:控制 'pictureBox1' 从比它on.`

堆栈跟踪创建的线程以外的线程访问如下:

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; 
    } 
+0

检查内部异常没有任何有用的信息。 – mcalex

回答

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); 
} 
相关问题