Why doesn't the timer start?

user6845869

It's simple code that increases a number and shows it in a texView but it's not working and I don't know what is wrong with my code...

here is my code:

protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);
        TextView textView = FindViewById<TextView>(Resource.Id.textView1);
        Timer timer1 = new Timer();
        timer1.Interval = 1000;
        timer1.Enabled = true;
        timer1.Start();
        timer1.Elapsed += (object sender, ElapsedEventArgs e) =>
         {
             x++;
             textView.Text = x.ToString();
         };
    }
SushiHangover

Since you are not using a SynchronizingObject, System.Timers.Timer is calling Elapsed on a threadpool thread, thus you are not on the UI/Main thread (where UI updates need to be performed).

So use RunOnUiThread to update your UI within the event:

timer1.Elapsed += (object sender, ElapsedEventArgs e) =>
{
    x++;
    RunOnUiThread(() => button.Text = x.ToString());
};

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related