Home > Back-end >  System.Timer weird behavior
System.Timer weird behavior

Time:10-21

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

CodePudding user response:

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.

  • Related