Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a timer running in the background without blocking the UI thread with Xamarin?

I want to run a block of code similar to the following code. The purpose of the code is to make an HTTP request at a one-second period without blocking the UI thread.

private void GetCodeFromTheServer()
{
   
     WebClient client = new WebClient();
    
     string code = client.DownloadString(new Uri(@"http://example.com/code"));
    
     Toast.MakeText(this, "Code: " + code, ToastLength.Long).Show();
}
like image 628
Firat Eski Avatar asked Nov 28 '14 22:11

Firat Eski


People also ask

How to start timer in Xamarin Forms?

To get started, here is the basic timer. Device. StartTimer(TimeSpan. FromSeconds(30), () => { // Do something return true; // True = Repeat again, False = Stop the timer });


1 Answers

If you need to do something at 1 second intervals, you might be able to use a timer for that. I have used code like this in Xamarin.Android myself:

   private void CountDown ()
    {

        System.Timers.Timer timer = new System.Timers.Timer();
        timer.Interval = 1000; 
        timer.Elapsed += OnTimedEvent;
        timer.Enabled = true;


    }

    private void OnTimedEvent(object sender, System.Timers.ElapsedEventArgs e)
    {

    }

OnTimedEvent will then fire every second and you can do your call in an async Task.

like image 67
DyreVaa Avatar answered Nov 10 '22 01:11

DyreVaa