我使用以下代码向数据库中的所有学生发送短信
private void btnsend_Click(object sender, EventArgs e)
{
foreach (Control c in Controls)
{
c.Enabled = false;
}
if (!bgw.IsBusy)
{
bgw.RunWorkerAsync();
}
}
private void bgw_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
Invoke((MethodInvoker)delegate()
{
using (var sp = new SerialPort(cbcomport.Text))
{
sp.Open();
sp.WriteLine("AT" + Environment.NewLine);
sp.WriteLine("AT+CMGF=1" + Environment.NewLine);
sp.WriteLine("AT+CMGS=\"" + dt.Rows[i]["PhoneNo"] + "\"" + Environment.NewLine);
sp.WriteLine(tbsms.Text + (char)26);
if (sp.BytesToRead > 0)
{
tbsentto.Text = i + 1 + " of " + dt.Rows.Count;
}
}
});
Thread.Sleep(5000);
}
}
private void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
foreach (Control c in Controls)
{
c.Enabled = true;
}
}
我的问题是:如果发生异常,例如端口“COM5”不存在,则会向学生发送短信。我想通过按钮重试和取消向用户显示相同的系统消息。如果已经解决了问题。即插入设备后,用户按下重试按钮,我想从同一点恢复线程,如果用户按下取消按钮,我想停止暂停的线程。