Firat Eski
Firat Eski

Reputation: 671

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();
}

Upvotes: 7

Views: 18239

Answers (2)

DyreVaa
DyreVaa

Reputation: 719

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.

Upvotes: 20

Ashu
Ashu

Reputation: 709

You will not be able make a call to web on Activity main thread. Use Async Task to execute your code. The Async Task will run in background and when the content is downloaded will show Toast for you. The sample below will help.

private class GetStringTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            String str = "...";
            /** String From Web **/
            return str;
        }

        @Override
        protected void onPostExecute(String address) {
            // Show Toast Here
        }
    }

Upvotes: 0

Related Questions