using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace SerialportTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private ChildForm childForm = null;
private void button1_Click(object sender, EventArgs e)
{
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.WorkerSupportsCancellation = true;
backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
childForm = new ChildForm();
backgroundWorker1.RunWorkerAsync();
childForm.ShowDialog(this);
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
MessageBox.Show(e.Error.Message);
return;
}
if (e.Cancelled)
{
childForm.label1.Text = "Cancelled!";
Thread.Sleep(1200);
backgroundWorker1.CancelAsync();
}
else
{
childForm.label1.Text = "Completed!";
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
childForm.progressBar1.Value = e.ProgressPercentage;//已将子窗体的progressbar设为public;
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
Thread.Sleep(0); //等待子窗体建立完毕;
for (int i = 0; i < 30; i++)
{
Thread.Sleep(200);
backgroundWorker1.ReportProgress(i * 100 / 30);
if (e.Cancel == true)
{
backgroundWorker1.CancelAsync();
}
}
backgroundWorker1.ReportProgress(100);
serialPort1.WriteLine("\n");
Thread.Sleep(2000);
MessageBox.Show(serialPort1.ReadExisting());
//这里老是为空.我的串口不用backgroundworker的话(调用一个普通方法)可以测试通过!
//我在考虑是不是改为同步阻塞读取,因为ReadExisting()是异步读取.
}
}
}