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

android, c#, multithreading, xamarin

Solution

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
        }
    }

Problem

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

Original source