我在c#中创建了一个应用程序,它在定义的时间间隔后发送短信,为此我使用计时器和一个计算记录数量(已发送消息)的标签。现在,当我点击提交按钮开始发送短信时,它从数据库中取出记录,但当它到达显示短信数量的标签部分时,它会显示一条错误消息 System.InvalidOperationExecution跨线程操作无效控件'lblXXX'从其创建的线程以外的线程访问。 我的代码是 For Button
private void btnSend_Click(object sender, EventArgs e)
{
this.btnSend.Enabled = false;
this.starttimer();
}
适用于计时器
private void starttimer()
{
System.Timers.Timer timer = new System.Timers.Timer();
timer.Start();
timer.Interval = 3000;
timer.Elapsed += new ElapsedEventHandler(this.time_elapsed);
}
Lable的
while (this.dr.Read())
{
this.lblWeightSMS.Text = Convert.ToString(Convert.ToInt32(this.lblWeightSMS.Text) + 1);
答案 0 :(得分:2)
您需要在UI线程上调用该调用。试试这个:
public void SetLblWeight(string lblWeight)
{
if (this.lblWeightSMS.InvokeRequired)
{
this.lblWeightSMS.Invoke(new Action<string>(SetLblWeight), lblWeight);
return;
}
this.lblWeightSMS.Text = lblWeight;
}
您的第this.lblWeightSMS.Text = ...
行将成为SetLblWeight(Convert.ToString(Convert.ToInt32(this.lblWeightSMS.Text) + 1);