0

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

2 Answers 2

0

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.
        }
    }
1
  • You might find in some edge cases the UI not updating with the last set of results depending on when the last ProgressChange is raised since the logic is built into that event handler.
    – aqwert
    Oct 7, 2012 at 23:25
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.