我的班级启动新进程(Tshark)并开始捕获,从主要表单我检查类属性以更新我的GUI,有时收到的数据包率我高到我的GUI卡住所以我想要选项每1-2秒检查一次属性。 这是我的进度更改功能,他一直在检查我的课程,在这一点上我更新了我的GUi,我怎么能每隔2秒检查一下这些属性?
Tshark tshark = new Tshark();
private void bgWSniffer_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
tshark = e.UserState as Tshark;
lblNumberOfReceivedPackets.Text = tshark._receivesPackets.ToString("#,##0");
lblTrafficRate.Text = (tshark._bitsPerSecond * 0.000001).ToString("0.##") + " Mbit/sec" + " (" + tshark._bitsPerSecond.ToString("#,##0") + " Bits/sec" + ")";
lblPacketsRate.Text = tshark._packetsPerSecond.ToString("#,##0") + " Packets/sec";
lblStatus.Text = tshark._status;
lblFileSize.Text = formatBytes(tshark._myFile.Length);
tshark._myFile.Refresh();
}
答案 0 :(得分:0)
检查自上次检查后是否已过去2秒。在这里,我正在使用班级成员来处理这段时间。
private DateTime _LastCheck = DateTime.MinValue;
private private void bgWSniffer_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if (_LastCheck.AddSeconds(2) <= DateTime.Now)
{
_LastCheck = DateTime.Now;
// do the UI update.
}
}
答案 1 :(得分:0)
而不是更新BackgroundWorker
中的UI,您只需创建一个Timer来完成工作
private void bgWSniffer_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
tshark = e.UserState as Tshark;
}
在ctor中创建计时器:
_timer = new Timer()
_timer.Intrerval = 2000;
_timer.Tick += UpdateUI;
_timer.Start();
如果值已更改,您可以添加一些检查,这样您就不会不必要地更新UI:
private void UpdateUI()
{
var local = _tshark;
if(local != null)
{
lblNumberOfReceivedPackets.Text = local._receivesPackets.ToString("#,##0");
lblTrafficRate.Text = (local._bitsPerSecond * 0.000001).ToString("0.##") + " Mbit/sec" + " (" + local._bitsPerSecond.ToString("#,##0") + " Bits/sec" + ")";
lblPacketsRate.Text = local._packetsPerSecond.ToString("#,##0") + " Packets/sec";
lblStatus.Text = local._status;
lblFileSize.Text = formatBytes(local._myFile.Length);
local._myFile.Refresh();
}
}