Results 1 to 9 of 9

Thread: [RESOLVED] Timer With KeyPress Event Lag Problem

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Oct 2012
    Posts
    166

    Resolved [RESOLVED] Timer With KeyPress Event Lag Problem

    Hello everyone.
    I'm making the hang man game in vb.net and it's pretty much functional and complete, just a few tweaks to be made.

    After the player solves the riddle a new form will appear displaying the total and current scores of both players and this is where the problem will be in effect.

    While optimizing the application, I encountered a lag issue which pretty much breaks down the score updating function.
    My function is based on win streaks and the elapsed time of the riddle solving.

    If the player, which is trying to solve the riddle, either writes too fast or traps a key for an undefinable time, the tick event of the timer will not fire, thus the seconds that have passed will not be sum and that pretty much ruins any real calculation by the function that calculates the scores.

    Here's the code that allows the player to type any letter from the keyboard:

    vb.net Code:
    1. Try
    2.             Dim Alphabet As List(Of String) = New List(Of String)
    3.  
    4.             For i As Int16 = Convert.ToInt16("A"c) To Convert.ToInt16("Z"c)
    5.                 Dim letter As Char = Convert.ToChar(i)
    6.                 Alphabet.Add(letter)
    7.             Next
    8.  
    9.             For Each btn As Control In CType(sender, fHangMan).Panel1.Controls
    10.                 If btn Is CType(sender, fHangMan).Panel1.Controls(btn.Name) Then
    11.                     If Alphabet.Contains(CChar(CType(btn, Button).Text)) Then
    12.                         If CChar(e.KeyChar.ToString.ToUpper) = CChar(CType(btn, Button).Text) Then
    13.                             CType(btn, Button).PerformClick()
    14.                         Else
    15.                             e.Handled = True
    16.                         End If
    17.                     End If
    18.                 End If
    19.             Next
    20.         Catch ex As Exception
    21.  
    22.         End Try

    Next we have the code for when any button, that has a letter, is clicked. After a button is clicked the corresponding letter will be drawn on a label, matching the position of the riddle, if that letter exists:

    vb.net Code:
    1. Private Sub btn_Click(ByVal sender As Object, e As EventArgs)
    2.         Try
    3.             Dim oldIndex As Integer = 0
    4.  
    5.             If mKeyPhrase.Contains(CType(sender, Button).Text) Then
    6.                 For i As Integer = 0 To mKeyPhrase.Length - 1
    7.                     If CChar(CType(sender, Button).Text) = mKeyPhrase.ElementAt(i) Then
    8.                         oldIndex = i
    9.                         For Each lbl As Control In CType(sender, Button).Parent.Controls
    10.                             If TypeOf lbl Is Label Then
    11.                                 If CType(lbl, Label).Name = CStr("lbl" & oldIndex) Then
    12.                                     CType(lbl, Label).Text = CChar(mKeyPhrase.ElementAt(i))
    13.                                     numberOfFoundChars += 1
    14.                                 End If
    15.                             End If
    16.                         Next
    17.                     End If
    18.                 Next
    19.                 CType(sender, Button).Enabled = False
    20.                 CType(sender, Button).Text = String.Empty
    21.             Else
    22.                 numberOfMisses += 1
    23.                 For Each pictBoxPan As Control In CType(sender, Button).Parent.Parent.Parent.Parent.Parent.Parent.Controls
    24.                     If TypeOf pictBoxPan Is SplitContainer Then
    25.                         For Each pictBox As Control In CType(pictBoxPan, SplitContainer).Panel2.Controls
    26.                             If TypeOf pictBox Is PictureBox Then
    27.                                 MissingLetter(pictBox)
    28.                             End If
    29.                         Next
    30.                     End If
    31.                 Next
    32.                 CType(sender, Button).Enabled = False
    33.  
    34.                 If numberOfMisses >= 6 Then
    35.                     For Each btn As Control In CType(sender, Button).Parent.Controls
    36.                         If TypeOf btn Is Button Then
    37.                             CType(btn, Button).Enabled = False
    38.                         End If
    39.                     Next
    40.                 End If
    41.             End If
    42.         Catch ex As Exception
    43.  
    44.         End Try
    45.     End Sub

    Here's the bit of code responsible for the score displaying for the players:

    vb.net Code:
    1. Try
    2.             If mPlayerTurn = 0 Then
    3.                 If CalculateDificulty(pKeyPhrase, pCategory) >= 1 And CalculateDificulty(pKeyPhrase, pCategory) <= 3 Then
    4.                     If mWinsStreak >= 2 Then
    5.                         Player1CurScore += 500 + mWinsStreak * (125 + 125) - (CInt(Math.Round((((500 + mWinsStreak * (125 + 125)) / (mTotalNumberOfSeconds * (500 + 125))) * 100), 0, MidpointRounding.ToEven)))
    6.                     Else
    7.                         Player1CurScore += 500 + 125 - (CInt(Math.Round((((500 + 125) / (mTotalNumberOfSeconds * (500 + 125))) * 100), 0, MidpointRounding.ToEven)))
    8.                     End If
    9.                 ElseIf CalculateDificulty(pKeyPhrase, pCategory) >= 4 And CalculateDificulty(pKeyPhrase, pCategory) <= 6 Then
    10.                     If mWinsStreak >= 2 Then
    11.                         Player1CurScore += 500 + mWinsStreak * (125 + 250) - (CInt(Math.Round((((500 + mWinsStreak * (125 + 250)) / (mTotalNumberOfSeconds * (500 + 250))) * 100), 0, MidpointRounding.ToEven)))
    12.                     Else
    13.                         Player1CurScore += 500 + 250 - (CInt(Math.Round((((500 + 250) / (mTotalNumberOfSeconds * (500 + 250))) * 100), 0, MidpointRounding.ToEven)))
    14.                     End If
    15.                 ElseIf CalculateDificulty(pKeyPhrase, pCategory) >= 7 And CalculateDificulty(pKeyPhrase, pCategory) <= 9 Then
    16.                     If mWinsStreak >= 2 Then
    17.                         Player1CurScore += 500 + mWinsStreak * (125 + 375) - (CInt(Math.Round((((500 + mWinsStreak * (125 + 375)) / (mTotalNumberOfSeconds * (500 + 375))) * 100), 0, MidpointRounding.ToEven)))
    18.                     Else
    19.                         Player1CurScore += 500 + 375 - (CInt(Math.Round((((500 + 375) / (mTotalNumberOfSeconds * (500 + 375))) * 100), 0, MidpointRounding.ToEven)))
    20.                     End If
    21.                 ElseIf CalculateDificulty(pKeyPhrase, pCategory) = 10 Then
    22.                     If mWinsStreak >= 2 Then
    23.                         Player1CurScore += 500 + mWinsStreak * (125 + 500) - (CInt(Math.Round((((500 + mWinsStreak * (125 + 500)) / (mTotalNumberOfSeconds * (500 + 500))) * 100), 0, MidpointRounding.ToEven)))
    24.                     Else
    25.                         Player1CurScore += 500 + 500 - (CInt(Math.Round((((500 + 500) / (mTotalNumberOfSeconds * (500 + 500))) * 100), 0, MidpointRounding.ToEven)))
    26.                     End If
    27.                 End If
    28.                 Player1TotalScore += Player1CurScore
    29.             ElseIf mPlayerTurn = 1 Then
    30.                 If CalculateDificulty(pKeyPhrase, pCategory) >= 1 And CalculateDificulty(pKeyPhrase, pCategory) <= 3 Then
    31.                     If mWinsStreak >= 2 Then
    32.                         Player2CurScore += 500 + mWinsStreak * (125 + 125) - (CInt(Math.Round((((500 + mWinsStreak * (125 + 125)) / (mTotalNumberOfSeconds * (500 + 125))) * 100), 0, MidpointRounding.ToEven)))
    33.                     Else
    34.                         Player2CurScore += 500 + 125 - (CInt(Math.Round((((500 + 125) / (mTotalNumberOfSeconds * (500 + 125))) * 100), 0, MidpointRounding.ToEven)))
    35.                     End If
    36.                 ElseIf CalculateDificulty(pKeyPhrase, pCategory) >= 4 And CalculateDificulty(pKeyPhrase, pCategory) <= 6 Then
    37.                     If mWinsStreak >= 2 Then
    38.                         Player2CurScore += 500 + mWinsStreak * (125 + 250) - (CInt(Math.Round((((500 + mWinsStreak * (125 + 250)) / (mTotalNumberOfSeconds * (500 + 250))) * 100), 0, MidpointRounding.ToEven)))
    39.                     Else
    40.                         Player2CurScore += 500 + 250 - (CInt(Math.Round((((500 + 250) / (mTotalNumberOfSeconds * (500 + 250))) * 100), 0, MidpointRounding.ToEven)))
    41.                     End If
    42.                 ElseIf CalculateDificulty(pKeyPhrase, pCategory) >= 7 And CalculateDificulty(pKeyPhrase, pCategory) <= 9 Then
    43.                     If mWinsStreak >= 2 Then
    44.                         Player2CurScore += 500 + mWinsStreak * (125 + 375) - (CInt(Math.Round((((500 + mWinsStreak * (125 + 375)) / (mTotalNumberOfSeconds * (500 + 375))) * 100), 0, MidpointRounding.ToEven)))
    45.                     Else
    46.                         Player2CurScore += 500 + 375 - (CInt(Math.Round((((500 + 375) / (mTotalNumberOfSeconds * (500 + 375))) * 100), 0, MidpointRounding.ToEven)))
    47.                     End If
    48.                 ElseIf CalculateDificulty(pKeyPhrase, pCategory) = 10 Then
    49.                     If mWinsStreak >= 2 Then
    50.                         Player2CurScore += 500 + mWinsStreak * (125 + 500) - (CInt(Math.Round((((500 + mWinsStreak * (125 + 500)) / (mTotalNumberOfSeconds * (500 + 500))) * 100), 0, MidpointRounding.ToEven)))
    51.                     Else
    52.                         Player2CurScore += 500 + 500 - (CInt(Math.Round((((500 + 500) / mTotalNumberOfSeconds * (500 + 500)) * 100), 0, MidpointRounding.ToEven)))
    53.                     End If
    54.                 End If
    55.                 Player2TotalScore += Player2CurScore
    56.             End If
    57.  
    58.             P1CurScore.Text = CStr(Player1CurScore)
    59.             P1TotScore.Text = CStr(Player1TotalScore)
    60.             P2CurScore.Text = CStr(Player2CurScore)
    61.             P2TotScore.Text = CStr(Player2TotalScore)
    62.         Catch ex As Exception
    63.  
    64.         End Try

    Note: The CalculateDificulty is just a function that finds out the level of dificulty of the riddle, based on the category chosed OR NOT and the text length of the riddle. Then, according to that level, a bonus is provided to the "riddle solver" player, that is if he or she solves the riddle.

    After the "riddle maker" creates the riddle, he just clicks a button to lock his/her riddle. After the lock, the "riddle solver" player will have the "Ready" button for whenever he/she's ready to start guessing the riddle. After pressing the button the timer starts running and the KeyPress event is activated.

    Here's the code, that describes the above:

    vb.net Code:
    1. Private Sub btnRiddleSolverReady_Click(sender As Object, e As EventArgs) Handles btnRiddleSolverReady.Click
    2.         Try
    3.             HMManager.CharacterListPlaceHolder(Panel1)
    4.             HMManager.ConstructCharSlots(Panel1)
    5.  
    6.             btnRiddleSolverReady.Enabled = False
    7.             btnRiddleSolverReady.Visible = False
    8.  
    9.             tmrPlayTime.Start()
    10.             tmrCheckGameStatus.Start()
    11.  
    12.             If HMManager.pPlayerTurn = 0 Then
    13.                 HMManager.pPlayerTurn = 1
    14.             ElseIf HMManager.pPlayerTurn = 1 Then
    15.                 HMManager.pPlayerTurn = 0
    16.             End If
    17.         Catch ex As Exception
    18.  
    19.         End Try
    20.     End Sub

    Here's the code for when the Tick Event of the tmrPlayTime timer is triggered:

    vb.net Code:
    1. Private Sub tmrPlayTime_Tick(sender As Object, e As EventArgs) Handles tmrPlayTime.Tick
    2.         Try
    3.             If elapsedMinutes >= 59 Then
    4.                 elapsedHours += 1
    5.                 elapsedMinutes = 0
    6.             Else
    7.                 If elapsedSeconds >= 59 Then
    8.                     elapsedSeconds = 0
    9.                     elapsedMinutes += 1
    10.                 Else
    11.                     elapsedSeconds += 1
    12.                 End If
    13.             End If
    14.  
    15.             If elapsedHours >= 10 Then
    16.                 If elapsedMinutes >= 10 Then
    17.                     If elapsedSeconds >= 10 Then
    18.                         Label3.Text = elapsedHours & ":" & elapsedMinutes & ":" & elapsedSeconds
    19.                     Else
    20.                         Label3.Text = elapsedHours & ":" & elapsedMinutes & ":0" & elapsedSeconds
    21.                     End If
    22.                 Else
    23.                     If elapsedSeconds >= 10 Then
    24.                         Label3.Text = elapsedHours & ":0" & elapsedMinutes & ":" & elapsedSeconds
    25.                     Else
    26.                         Label3.Text = elapsedHours & ":0" & elapsedMinutes & ":0" & elapsedSeconds
    27.                     End If
    28.                 End If
    29.             Else
    30.                 If elapsedMinutes >= 10 Then
    31.                     If elapsedSeconds >= 10 Then
    32.                         Label3.Text = "0" & elapsedHours & ":" & elapsedMinutes & ":" & elapsedSeconds
    33.                     Else
    34.                         Label3.Text = "0" & elapsedHours & ":" & elapsedMinutes & ":0" & elapsedSeconds
    35.                     End If
    36.                 Else
    37.                     If elapsedSeconds >= 10 Then
    38.                         Label3.Text = "0" & elapsedHours & ":0" & elapsedMinutes & ":" & elapsedSeconds
    39.                     Else
    40.                         Label3.Text = "0" & elapsedHours & ":0" & elapsedMinutes & ":0" & elapsedSeconds
    41.                     End If
    42.                 End If
    43.             End If
    44.         Catch ex As Exception
    45.  
    46.         End Try

    At this stage, if you're wondering what the "tmrCheckGameStatus" is and does, it's just another timer which is responsible for checking the current status of the game, validating how many slots are still blank for the riddle and how many misses were hit by the "riddle solver" player. Whenever the game end, in other words, when there's no more blank slots to be filled, this timer calls the form that is in charge of triggering the "DisplayScores" procedure, which will display a new window with the scores of both players.

    What I thought I could do to solve the lag problem with the KeyPress event and the timer, would be to implement multithreading, where the timer would be processed in another thread.
    I just have no clue on how to do it, I've tried to use delegates, but the result is still the same, the timer still freezes under the same certain conditions of the KeyPress event, previously described.

    Is there anyone that can point me out any way to solve this issue? I'm open to use anything, be it multi-threading or not. At this point, the simpler the better.

    Note to readers: If there's anything I failed to describe or if the text is confusing, let me know what you need me to explain better.

  2. #2
    Fanatic Member
    Join Date
    Sep 2002
    Posts
    527

    Re: Timer With KeyPress Event Lag Problem

    Hi Simbiose.

    If you are using the timer tick event to increment your ellapse time every time it ticks, that's where your problem is. You should save the current time in a Date variable when the game starts, and just substract that value to 'Now' when the timer ticks to get a TimeSpan value. Then, use TimeSpan ToString function to display that on your form. I think that would help you greatly.

    That said, I'm not completely sure I fully undertsand what your code does in that event, so maybe I'm off track. How is
    Last edited by Alain; Feb 9th, 2015 at 09:55 AM.
    Don't ask why, just reboot!

  3. #3
    Fanatic Member
    Join Date
    Sep 2002
    Posts
    527

    Re: Timer With KeyPress Event Lag Problem

    Another thing I hadn't notice at first. Although it is not directly related to your problem, you are swallowing errors, meaning you don't have anything Between the 'Catch' statement and the 'End Try' statement. So any errors that your code will generate won't show at all. You should at least put a messagebox in there, if it's just to warn you something happen. Better yet, have it display ex.message to have a slight idea of what the error is.
    Don't ask why, just reboot!

  4. #4

    Thread Starter
    Addicted Member
    Join Date
    Oct 2012
    Posts
    166

    Re: Timer With KeyPress Event Lag Problem

    Quote Originally Posted by Alain View Post
    Hi Simbiose.

    If you are using the timer tick event to increment your ellapse time every time it ticks, that's where your problem is. You should save the current time in a Date variable when the game starts, and just substract that value to 'Now' when the timer ticks to get a TimeSpan value. Then, use TimeSpan ToString function to display that on your form. I think that would help you greatly.

    That said, I'm not completely sure I fully undertsand what your code does in that event, so maybe I'm off track. How is
    Hey Alain,

    Thanks for your time. I was actually hyped, cause your suggestion was, to me, the ideal solution to solve my problem.
    However, when I run the app after changing the code, I still get the same lag

    And now that I think of it, I believe I know where the lag is coming from.
    When I dynamically create a button, I also dynamically created the handler for the "Click" Event, just as the "KeyPress" Event and here's what happens on those two:

    Click Event Handler

    vb.net Code:
    1. Private Sub btn_Click(ByVal sender As Object, e As EventArgs)
    2.         Try
    3.             Dim oldIndex As Integer = 0
    4.  
    5.             If mKeyPhrase.Contains(CType(sender, Button).Text) Then
    6.                 For i As Integer = 0 To mKeyPhrase.Length - 1
    7.                     If CChar(CType(sender, Button).Text) = mKeyPhrase.ElementAt(i) Then
    8.                         oldIndex = i
    9.                         For Each lbl As Control In CType(sender, Button).Parent.Controls
    10.                             If TypeOf lbl Is Label Then
    11.                                 If CType(lbl, Label).Name = CStr("lbl" & oldIndex) Then
    12.                                     CType(lbl, Label).Text = CChar(mKeyPhrase.ElementAt(i))
    13.                                     numberOfFoundChars += 1
    14.                                 End If
    15.                             End If
    16.                         Next
    17.                     End If
    18.                 Next
    19.                 CType(sender, Button).Enabled = False
    20.                 CType(sender, Button).Text = String.Empty
    21.             Else
    22.                 numberOfMisses += 1
    23.                 For Each pictBoxPan As Control In CType(sender, Button).Parent.Parent.Parent.Parent.Parent.Parent.Controls
    24.                     If TypeOf pictBoxPan Is SplitContainer Then
    25.                         For Each pictBox As Control In CType(pictBoxPan, SplitContainer).Panel2.Controls
    26.                             If TypeOf pictBox Is PictureBox Then
    27.                                 MissingLetter(pictBox)
    28.                             End If
    29.                         Next
    30.                     End If
    31.                 Next
    32.                 CType(sender, Button).Enabled = False
    33.  
    34.                 If numberOfMisses >= 6 Then
    35.                     For Each btn As Control In CType(sender, Button).Parent.Controls
    36.                         If TypeOf btn Is Button Then
    37.                             CType(btn, Button).Enabled = False
    38.                         End If
    39.                     Next
    40.                 End If
    41.             End If
    42.         Catch ex As Exception
    43.  
    44.         End Try

    KeyPress Event Handler

    vb.net Code:
    1. Private Sub btn_KeyPress(ByVal sender As Object, e As KeyPressEventArgs)
    2.         Try
    3.             Dim Alphabet As List(Of String) = New List(Of String)
    4.  
    5.             For i As Int16 = Convert.ToInt16("A"c) To Convert.ToInt16("Z"c)
    6.                 Dim letter As Char = Convert.ToChar(i)
    7.                 Alphabet.Add(letter)
    8.             Next
    9.  
    10.             For Each btn As Control In CType(sender, fHangMan).Panel1.Controls
    11.                 If btn Is CType(sender, fHangMan).Panel1.Controls(btn.Name) Then
    12.                     If Alphabet.Contains(CChar(CType(btn, Button).Text)) Then
    13.                         If CChar(e.KeyChar.ToString.ToUpper) = CChar(CType(btn, Button).Text) Then
    14.                             CType(btn, Button).PerformClick()
    15.                         Else
    16.                             e.Handled = True
    17.                         End If
    18.                     End If
    19.                 End If
    20.             Next
    21.         Catch ex As Exception
    22.  
    23.         End Try
    24.     End Sub

    As you can see on the blocks of code shown above, a lot of validations are being processed. Furthermore there will be a loop for each button and label in order to validate if the key being pressed matches any letter on the riddle string.
    To my point of view a lot of memory is being used on run-time for these events, therefor when the user presses a key on the keyboard, the application just pretty much "chokes", not letting any other control to be processed, such as the timer.

    I have no idea what approach I should take to avoid this.

    About the Try Catch statements, it's no problem. I know I'm not displaying any messagebox to show the exceptions that are being thrown at run-time, mainly because i can still see the exceptions while debugging. I've just place the try catch statements there, so that i remember later on to code them.

  5. #5
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    38,988

    Re: Timer With KeyPress Event Lag Problem

    You should do something in the Catch block, even if it is just putting up a message. After all, a thrown exception is horribly costly in time. Of course, if you have CLR Exceptions set to break when thrown, you will see all the exceptions, but you need to do something, because the code you have shown doesn't seem likely to take any time at all. Upon further thought, you should get rid of the exception handling entirely. There is nothing in that code that should throw an exception unless there is a straight up bug in the code. You are better off fixing the bugs than you are catching exceptions and trying to deal with them that way.

    You really need to identify where the lag is. Exceptions being thrown is a likely one, but you don't need to be guessing. Add a Stopwatch object at form scope and use that to time different parts of the code. Alternatively, I have a class in the .NET CodeBank called a Lightweight Profiler, which is just a class wrapped around a stopwatch that allows you to add multiple different timing tokens to time different parts of the code. In either case, the Stopwatch is a precision timer with sub-millisecond resolution, and that's pretty much what you need to do.

    You could improve the efficiency of the code a bit, but there is nothing that really jumps out at me. For one thing, you keep CTypeing things, and that's a waste of time. If sender is fHangMan, then use DirectCast (faster than CType) to convert it one time, and don't keep using it every time you want to turn sender into fHangMan. Still, CType is really fast, so making that change shouldn't save you more than a millisecond, and probably won't save even that much. You also don't need that For loop that fills Alphabet, because you could move Alphabet to form scope, fill it in the load event, and just use it without filling it over and over. Still, that loop should take a hundredth of a millisecond, or less, so it makes little difference.

    Overall, I'd say that, if you did some timing of the code using a Stopwatch, you'd probably find that the code runs in a millisecond or less. So, unless you are throwing exceptions, the code you showed shouldn't have any lag at all.
    My usual boring signature: Nothing

  6. #6

    Thread Starter
    Addicted Member
    Join Date
    Oct 2012
    Posts
    166

    Re: Timer With KeyPress Event Lag Problem

    Hey Shaggy,

    Thank you for your time. What you've written makes perfect sense, though I hadn't thought about that.
    So I went on following your steps and tried to use the stopwatch class (I had no idea such a class existed -_-), but it appears that everything done on the KeyPress and Click events always return a total time of 0 seconds?!?!

    Since I got stumped on this, I went on searching for a Lightweight Profiler app and I download a trial version of DotTrace, but I have no idea on how to use it. Care to explain a bit to get me started? In the meantime I'll try to figure it out on my own.

    An extra note, I found out some incongruencies on my code. For instance my for loops would keep running even though the correct match was already found, a clear mistake
    I've written exits for the loops on every possible location of the code and it appears that both the KeyPress and Click events gotten faster.
    As of now if a user presses and holds any of the keys the timer still keeps running, which I believe I'm on the right track.
    However, if a user still types too fast, the timer freezes and it lags out, where you can actually see the app running through the Paint Event of the disabling and clearing of the button.

    ***UPDATE***
    Ehmm.. ok... sooooo, yeah... What if I told you that I get no lag if I run the application through the executable rather through debugging with Visual Studio?
    I managed to figure out how to work with DotTrace and, when analysing the performance of my application, it was just like Shaggy mentioned. The events cost aproximatelly 76 ms altogether, not even close to a second, so it just wasn't making sense the fact that the events were lagging, furthermore while running the application through DotTrace, I noticed that there was no lag when I fast typed the riddle, which strucked me down...

    Well, in fact, it made perfect sense that the application was lagging, but I thought it for the wrong reasons.
    The problem was not on my code, neither on the app performance.

    My next step was to monitorize my machine performance while running the app through Visual Studio and then again, but by starting the executable. I verified that for the former case, the application was in normal state compared to the latter. So what was the difference?
    My machine has 8 cores, where 5 of them were being overused by Visual Studio, which is kinda worrying me, since this is the tool I use for my projects all the time and I'm probably getting a false reality of how my applications are working :|
    In other words when I think everything is right, it might probably not be at all ...
    I'm having a bad feeling that Visual Studio itself has a memory leak somewhere or something, causing the applications not to run properly.
    Last edited by Simbiose; Feb 10th, 2015 at 08:08 AM.

  7. #7
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    38,988

    Re: Timer With KeyPress Event Lag Problem

    The LightWeight Profiler that I mentioned was a class posted in a thread in the CodeBank (search on my name and Profiler and you'll find it). It's what I use for timing.

    I'm not at all surprised that you measured 0 milliseconds (and even less surprised if you measured 0 seconds). When I test the speed of code constructs, such as comparing CType to Directcast, I have to run a loop through tens of thousands and tens of millions of iterations to get the speed difference high enough to detect (a few milliseconds). So, one iteration might take a thousandth of a a millisecond. You are only timing one iteration of the code. If you put a Stopwatch on the form, started the Stopwatch at the start of one of those routines, stopped it at the end, and ended up with an elapsed time of 0 milliseconds, that's exactly what I would expect. I don't believe the code you showed will take even a single millisecond, and it sounds like that is exactly what you are finding. The time taken is too fast even for a precision timer, and that's the point: The lag has nothing to do with the code you showed.

    The one exception to this would be if you were actually throwing exceptions. Those are seriously slow, which is why I suggested getting rid of the exception handling, because you WANT the program to crash (in those methods, at least, not in ALL cases) so that you can find and fix any bugs in that code. If you aren't getting exceptions, and those methods are running in a fraction of a millisecond, and you are seeing a lag....then the lag isn't related to that code. Of course, that also means that diagnosing the problem will be more difficult.
    My usual boring signature: Nothing

  8. #8

    Thread Starter
    Addicted Member
    Join Date
    Oct 2012
    Posts
    166

    Re: Timer With KeyPress Event Lag Problem

    Quote Originally Posted by Shaggy Hiker View Post
    The LightWeight Profiler that I mentioned was a class posted in a thread in the CodeBank (search on my name and Profiler and you'll find it). It's what I use for timing.

    I'm not at all surprised that you measured 0 milliseconds (and even less surprised if you measured 0 seconds). When I test the speed of code constructs, such as comparing CType to Directcast, I have to run a loop through tens of thousands and tens of millions of iterations to get the speed difference high enough to detect (a few milliseconds). So, one iteration might take a thousandth of a a millisecond. You are only timing one iteration of the code. If you put a Stopwatch on the form, started the Stopwatch at the start of one of those routines, stopped it at the end, and ended up with an elapsed time of 0 milliseconds, that's exactly what I would expect. I don't believe the code you showed will take even a single millisecond, and it sounds like that is exactly what you are finding. The time taken is too fast even for a precision timer, and that's the point: The lag has nothing to do with the code you showed.

    The one exception to this would be if you were actually throwing exceptions. Those are seriously slow, which is why I suggested getting rid of the exception handling, because you WANT the program to crash (in those methods, at least, not in ALL cases) so that you can find and fix any bugs in that code. If you aren't getting exceptions, and those methods are running in a fraction of a millisecond, and you are seeing a lag....then the lag isn't related to that code. Of course, that also means that diagnosing the problem will be more difficult.
    Well, I ended up clearing everything that wasn't needed, polished everything and removed the try catch blocks, tested the app and it still performs the same lag on Visual Studio and then I ran the app through the executable yet again and through there and there's no lag.
    I can only assume the problem comes from Visual Studio, using up a lot of resources on my machine, I can't think of anything else, since what I described on my previous post.

    I'm gonna mark this thread as answered, cause my application is working 100% and no lag if I ran through the executable, even though I don't feel too secure about this :|

  9. #9
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    38,988

    Re: [RESOLVED] Timer With KeyPress Event Lag Problem

    Is your machine very low on RAM?

    I'm not sure how low you'd have to be. I've had no issues with VS running on Win7 with only 2GB RAM, so you' have to either have LOTS of other things going on, or you'd have to have even less memory.

    Having said that, I feel more confident than you do that the lag is a VS thing, I just don't think you can blame a lack of resources. There are things that just happen, at times. Perhaps some internal switch was causing it to recompile the app consistently at that point. I have an application that performs MUCH different (and much worse) the first time I run it in VS on any given day. It doesn't matter whether I have made changes or not, the first time it runs there is a significant lag at one point and then never again until I reboot the computer. This is almost certainly due to something being swapped to or from the HD, but it doesn't happen for any other program, and it doesn't happen all that early in this program. So, I wouldn't worry about it too much unless it starts appearing outside of VS.
    My usual boring signature: Nothing

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width