让我们模拟硬件:
public class Hardware
{
System.Timers.Timer _timer;
public event EventHandler Send;
public Hardware()
{
_timer = new System.Timers.Timer();
_timer.Interval = 1000;
_timer.Elapsed += _timer_Elapsed;
_timer.Start();
}
void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
Send(this, new SendArgs(DateTime.Now.Ticks));
}
public class SendArgs : EventArgs
{
public long Id { get; private set; }
public SendArgs(long id)
{
Id = id;
}
}
}
在您的主窗体中,您可以添加一个临时保存值的集合对象:
public partial class Form1 : Form
{
List<object> _queue = new List<object>();
bool _paused = false;
public Form1()
{
InitializeComponent();
dataGridView1.Columns.Add("Id", "Id");
var h = new Hardware();
h.Send += h_Send;
}
void h_Send(object sender, EventArgs e)
{
var value = ((Hardware.SendArgs)e).Id;
if (_paused)
{
_queue.Add(value);
}
else
{
if (this.InvokeRequired)
{
BeginInvoke(new MethodInvoker(delegate()
{
dataGridView1.Rows.Add(value);
}));
}
}
}
private void pauseButton_Click(object sender, EventArgs e)
{
_paused = !_paused;
pauseButton.Text = (_paused) ? "Start" : "Pause";
if (!_paused)
if (this.InvokeRequired)
{
BeginInvoke(new MethodInvoker(delegate()
{
_queue.ForEach(item =>
{
dataGridView1.Rows.Add(item);
});
_queue.Clear();
}));
}
else
{
_queue.ForEach(item =>
{
dataGridView1.Rows.Add(item);
});
_queue.Clear();
}
}
}
[编辑] 这是您更新问题中代码示例的版本:
List<object> _queue = new List<object>();
bool _paused = false;
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
string StrMSGdata = "";
string tStamp = "";
for (int i = 0; i < 100; i++)
{
StrMSGdata = i.ToString();
tStamp = DateTime.Now.ToLongTimeString();
backgroundWorker1.ReportProgress(i, StrMSGdata + "#" + tStamp);
Thread.Sleep(1000);
}
}
private void backgroundWorker1_ProgressChanged(
object sender, ProgressChangedEventArgs e)
{
string recived = e.UserState.ToString();
string[] fullMsgData = new string[15];
fullMsgData = recived.Split('#');
string msgData = fullMsgData[0];
string timStamp = fullMsgData[1];
if (_paused)
{
_queue.Add(new[]{ timStamp, msgData });
}
else
{
dataGridView1.Rows.Add(timStamp, msgData);
}
}
private void pauseButton_Click(object sender, EventArgs e)
{
_paused = !_paused;
pauseButton.Text = (_paused) ? "Start" : "Pause";
if (!_paused)
if (this.InvokeRequired)
{
BeginInvoke(new MethodInvoker(delegate()
{
_queue.ForEach(item =>
{
dataGridView1.Rows.Add(item);
});
_queue.Clear();
}));
}
else
{
_queue.ForEach(item =>
{
dataGridView1.Rows.Add((string[])item);
});
_queue.Clear();
}
}