Update UI Immediately from a 'System.Timers.Timer.Elapsed' event

Hello,

I'm new to Xamarin and I'm trying to change the text of a TextView inside an Elapsed event of a timer that runs every 200ms.

Here is my code currently:

`private void HandleElapsed (object sender, ElapsedEventArgs e)
{
this.CurrentWordIndex++;

if (this.CurrentWordIndex >= this.Words.Count) {
    this.Status = PlayerStatus.End;
    this.Timer.Stop ();
} else {
    Task.Factory.StartNew (() => {
        this.uiCurrentWordTextView.Text = this.Words [this.CurrentWordIndex]; //I'm trying to update the UI here
    }, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());
}

}`

A breakpoint on "Task.Factory.StartNew" does get hit but a breakpoint on "this.uiCurrentWordTextView.Text = this.Words [this.CurrentWordIndex];" doesn't.

Any help is appreciated.

Posts

  • CheesebaronCheesebaron DKInsider, University mod

    Why are you doing UI changes inside of a Task?

  • ChrisJohnson.8155ChrisJohnson.8155 USMember ✭✭

    I used to not have it in a task but the UI wasn't changing and I thought maybe the timer loop was doing something to the UI thread.

    What I need to do is loop through a list of strings, once every 200ms, and each time set the word to the textview.

  • ChrisJohnson.8155ChrisJohnson.8155 USMember ✭✭

    The code works when I take it out of the timer elapsed event such as putting it in a button click event.

    Why would the timer screw it up?

Sign In or Register to comment.