简体   繁体   中英

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

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

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

In the ctor create the timer:

_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:

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();      
   }  
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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