2

Sorry for confusion title but I honestly don't know what to put here. So I have created a timer which will fire an event every T interval. This simple event will just append the text and display it in a MMORPG style. It does work, but one thing is weird is that it sometime doesn't fire the event (am I explaining it right?).

Here is the picture so you can understand what I mean:

enter image description here

Here is my code:

baloon = new System.Timers.Timer(30);
baloon.Elapsed += OnTweakTimedEvent_baloon;
//baloon.Elapsed += new ElapsedEventHandler(OnTweakTimedEvent_baloon);

private void OnTweakTimedEvent_baloon(object sender, ElapsedEventArgs e)
{
    lbBaloon.Text += message[letterCount]; 
    letterCount++;
    if (letterCount > message.Length - 1) //stops timer when finishes
    {
        letterCount = 0;
        baloon.Enabled = false;
        lbBaloon.Text = message; // displays the full message when it ends
    }
 }
takatto
  • 63
  • 7
  • 2
    I wonder why you don't simply use `lblBaloon.Text = message.Substring(0, letterCount++);` – ProgrammingLlama Oct 20 '21 at 05:48
  • @Llama ah thanks for the marvelous idea haha, it did fix the missing letter problem but the animation is not really smooth, like when the weird thing on timer happens the animation is very laggy. I would accept your comment as answer if you made answer instead but still i would like to know what is the reason behind that weird behavior. – takatto Oct 20 '21 at 06:04
  • 1
    Timers are not really good to use for animating anything in winforms, Essentially you are at the limit of the precision of a timer and is surprising this is even working as well as it is anyway. – TheGeneral Oct 20 '21 at 06:15
  • 2
    _animation is not really smooth_ - Welcome to winforms :-( – TaW Oct 20 '21 at 06:56

1 Answers1

4

A rather obvious problem is that you are using a System.Timers.Timer for a UI, without any synchronization. Without a SynchronizationContext this timer will raise events on a background thread, and that may cause all kinds of issues since UI-classes are only safe to access by the UI thread.

I would recommend either using a SynchronizationContext or switch to a winforms timer. See timer comparison for more details.

JonasH
  • 28,608
  • 2
  • 10
  • 23