Timer callback event in UI Thread

lihuipeng49lihuipeng49 Member ✭✭✭

In console app I can use the code like this:

while(true)
{
    MyProc.Tick();
}

But in Xamarin.Forms the while(true) controlled by the UI system.
I want MyProc.Tick run in Xamarin.Forms ContentPage.
I think, maybe I need to use Timer for this.
But the timer callback event function run on other thread, not run on the UI thread.

In WPF there is an DispatcherTimer can invoke the event on UI thread.
I want to know what can invoke MyProc.Tick on UI thread in Xamarin.Forms?

Best Answers

Answers

  • lihuipeng49lihuipeng49 Member ✭✭✭

    MyProc.Tick() is just a example for the question .

    I use the following code to got a UI Thread timer callback successfully!

        public partial class MainPage : ContentPage
        {
            public MainPage()
            {
                Debug.WriteLine("MainPage Construct > CurrentThreadId = {0}", Thread.CurrentThread.ManagedThreadId);
    
                var span = new TimeSpan(0, 0, 1);
                Device.StartTimer(span, TimerTick);
            }
    
            private bool TimerTick()
            {
                Debug.WriteLine("MainPage TimerTick > CurrentThreadId = {0}", Thread.CurrentThread.ManagedThreadId);
    
                return true;
            }
        }
    

    This is the run output:

    [0:] MainPage Construct > CurrentThreadId = 1
    [0:] MainPage TimerTick > CurrentThreadId = 1
    [0:] MainPage TimerTick > CurrentThreadId = 1
    [0:] MainPage TimerTick > CurrentThreadId = 1
    
  • JohnHardmanJohnHardman GBUniversity mod

    @lihuipeng49 said:
    I use the following code to got a UI Thread timer callback successfully!

                Device.StartTimer(span, TimerTick);
    

    Did https://forums.xamarin.com/discussion/comment/376899/#Comment_376899 answer your question?

  • lihuipeng49lihuipeng49 Member ✭✭✭

    Sorry!
    This is the first time I know, the forum can mark 2 answers.

Sign In or Register to comment.