0

我的类启动新进程(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();            
}
4

2 回答 2

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.
        }
    }
于 2012-10-07T23:03:34.130 回答
0

BackgroundWorker您可以创建一个 Timer 来完成这项工作,而不是在其中更新 UI

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();      
   }  
}
于 2012-10-07T23:03:42.787 回答