简体   繁体   English

每隔几秒钟采样一次我的课程属性

[英]Sample my class properties every few seconds

my class start new process (Tshark) and start capturing, from the main form i am checking the class properties in order to update my GUI, sometimes the received packets rate i so high that my GUI stuck so i want the option to check whose properties every 1-2 second. 我的班级开始新进程(Tshark),并从主窗体开始捕获,我正在检查班级属性以更新我的GUI,有时收到的数据包速率很高,以至于我的GUI卡住了,所以我想选择检查其属性每1-2秒。 this is my progress change function who checking my class all the time and in this point i am update my GUi, how can i checking those properties every 2 seconds ? 这是我的进度更改功能,它始终检查我的班级,此时我正在更新我的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();            
}

Check if 2 seconds has passed since the last check. 自上次检查后是否经过了2秒。 Here, I'm using a class member to tract that time. 在这里,我正在使用班级成员来安排时间。

    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.
        }
    }

Instead of updating the UI within the BackgroundWorker you can just create a Timer to do the job 无需在BackgroundWorker中更新UI,您只需创建一个Timer即可完成工作

private void bgWSniffer_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    tshark = e.UserState as Tshark;
}

In the ctor create the timer: 在ctor中创建计时器:

_timer = new Timer()
_timer.Intrerval = 2000;
_timer.Tick += UpdateUI;
_timer.Start();

You can add some checking in case the values have changed so you don't update the UI needlessly: 如果值已更改,则可以添加一些检查,以免不必要地更新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();      
   }  
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM