Help creating an AsyncTask

I am trying to create an AsyncTask that will allow me to download content from a webpage in the background. This is what I have found to do in my research:
private class myTask extends AsyncTask<Void, Void, Void> {

    protected void onPreExecute() {


    protected Void doInBackground(Void... params) {
        // Runs on the background thread

        return null;

    protected void onPostExecute(Void res) {



I tried to create a new Android class and replace the contents with this but it is saying that 'extends' is invalid in the current context. Do I need to include any references to get this to work and if so how do I get them?

Best Answers


  • KlutchSCKlutchSC USMember

    I'm sorry to point out that the link you posted is also giving me Java code. I have never worked with Java and have no clue how to convert it into C#. Would you be so kind as to maybe explain what you mean by that or post a link that actually shows C# code since I cannot do the conversions simply?

  • KlutchSCKlutchSC USMember

    I am extremely sorry for my hasty reply but the code actually seems to be in C# after all. Call it my Jave-ignorance but I cannot see the difference between the two but I have a feeling it has to do with "Java.Lang.Object"

    is it as simple as including this to use java objects within C# code?

  • CheesebaronCheesebaron DKInsider, University mod

    Nevertheless, using AsyncTask is an ugly Java way of doing asynchronous tasks. There are better ways, without having to pass contexts, and other stuff to return things back to where you call it from.

  • chris_riesgochris_riesgo USUniversity ✭✭✭

    Is using C# Async/Await viable enough vs TPL or rolling one of these older "Java" formats?

  • TomOpgenorthTomOpgenorth CAXamarin Team Xamurai

    @chris_riesgo: Yes async/await is perfectly fine (and cleans up your code a lot, might I add).

  • chris_riesgochris_riesgo USUniversity ✭✭✭
    edited September 2013

    @topgenorth - awesome. I thought async/await was the new/preferred way if you could manage it, but it's good to have that feedback :)

  • rmaciasrmacias USBeta, University ✭✭✭✭✭

    At the time of the original posted question, async/await was not in the stable release. Now it is. :)

  • MaruMaru DEMember ✭✭

    This thread is rather old but I hope someone can add a few lines how to handle AsyncTasks with the tools now.
    I have a ListView and try to populate its ImageViews from an URL source.

  • TomOpgenorthTomOpgenorth CAXamarin Team Xamurai

    Maru - there really isn't much need to use AsyncTask in Xamarin.Android. Use async/await instead.

  • MaruMaru DEMember ✭✭

    Thanks for the reply Tom, but I looked already into it how to use async/await there but with no results. Can you guide me in the right direction? I know how to use these keywords but not in this scenario.

  • rmaciasrmacias USBeta, University ✭✭✭✭✭

    @Maru, you either use async/await (C#) way of doing things or you use the AsyncTask (Android), but not both. It's highly recommended you use async/await. Since you say you already know how to use the async/await keywords, that's all there is to it.

  • MaruMaru DEMember ✭✭
    edited May 2014

    @rmacias‌, I think my main problem is that I don't know a good way to handle the view recycle from a ListView because the GetView of my custom adapter is redownloading the images every time I scroll and fills new appearing ListItems with images from the previous recycled item.
    I have now a system when the image was downloaded (with async/await) the first time, I save it into the internal storage and display it from there any other time its shown. Additionally I removed the view recycling to get rid of the "old image showing" described above. But I have the feeling that this approach is not really what I should do...

  • ChristopherDrososChristopherDrosos GRMember ✭✭
    edited September 2015

    i was going to use this tutorial for my app but after readig this topic you think guys i should convert this tutorial from asynctask to async await?

  • ArnoldBoschArnoldBosch ZAMember ✭✭

    Old Post I know but this might be helpful to some people

     Task.Factory.StartNew(() =>
                       //Whatever you would like to do in background 
                   catch(Exception e)
                    // ContinueWith allows you to specify an action that runs after the previous thread
                    // completes
                    // By using TaskScheduler.FromCurrentSyncrhonizationContext, we can make sure that 
                    // this task now runs on the original calling thread, in this case the UI thread
                    // so that any UI updates are safe. in this example, we want to hide our overlay, 
                    // but we don't want to update the UI from a background thread.
               t =>
                 //do something else after the first task is done...
               }, TaskScheduler.FromCurrentSynchronizationContext()

    if you would like to pop something from this background thread to your UI thread please use

    RunOnUiThread(() => methodForUI());


    RunOnUiThread(() => ShowMessage(this,"Error","Actoin Not Complete"));

            /// <summary>
            /// <para>Populates a single message </para>
            /// </summary>
            /// <param name="c">this</param>
            /// <param name="title">string with Title</param>
            /// <param name="message">string with Message</param>
            public void ShowMessage(Android.Content.Context c,string title,string message)
                ad = new AlertDialog.Builder(c).Create();
  • i am using a twitter component. i want to post status on twitter. The post loads a lot on main thread therefore i want Async tasks. in my case asyn/await does work. the method does not support Async task (twitter.UpdateStatus("bla bla bla")). What should i do???

  • CheesebaronCheesebaron DKInsider, University mod

    @MuhammadWaqas what you should do is be more clear about your question. Probably create a new one, with the relevant information about your specific question.

  • if i have a method that has to be asyn but is not an asyn and i want to make it run under an async task. what should i do
    1. Make an Async Class
    2. use async/await

    async/await i not working with it actually

    For Example

    (twitter.updateStatus("Hello World"));
    i want this mehod to run on a separate thread.

  • OthmanahmadOthmanahmad USMember

    Hello everybody,
    her is my code how can i use AsyncTask class with onPreExecute() doInBackground() onPostExecute() Events, Please Help me with that ,i'm trying since yesterday :

    namespace solution
    [Activity(Label = "ApiActivity")]
    public class ApiActivity : Activity
    TextView textview;
    protected override void OnCreate(Bundle savedInstanceState)
    Button button = FindViewById(Resource.Id.button10);
    textview = FindViewById(Resource.Id.textView1);
    ProgressBar progressBar = FindViewById(Resource.Id.progressBar1);

            button.Click += async (sender, e) =>
                string url = "$top=5&$skip=5";
                JsonValue json = await FetchWeatherAsync(url);
        private void print(JsonValue json)
            int length = (int)json["value"].Count;
            textview.Text = "";
            for (int i = 0; i < length; i++)
                textview.Text += "ID     " + json["value"][i]["NewsArticleId"].ToString() + "\n";
                textview.Text += "Title    " + json["value"][i]["Title"].ToString() + "\n";
                textview.Text += "Description    " + json["value"][i]["Description"].ToString() + "\n";
                textview.Text += "Link    " + json["value"][i]["Link"].ToString() + "\n";
                textview.Text += "Published On     " + json["value"][i]["PublishedOn"].ToString() + "\n";
                textview.Text += "************************************" + "\n";
        private async Task<JsonValue> FetchWeatherAsync(string url)
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
            request.ContentType = "application/json";
            request.Method = "GET";
            using (WebResponse response = await request.GetResponseAsync())
                using (Stream stream = response.GetResponseStream())
                    JsonValue jsonDoc = await Task.Run(() => JsonObject.Load(stream));
                    return jsonDoc;


  • OthmanahmadOthmanahmad USMember

    **Hello everybody,
    her is my code how can i use AsyncTask class with onPreExecute() doInBackground() onPostExecute() Events, Please Help me with that ,i'm trying since yesterday : **

  • GaryParkinGaryParkin USMember ✭✭
    edited September 2016

    So what's the verdict? I'm starting a new Xamarin project that must support Android 5 (21). Do I use AsyncTask, or async/await?

  • Chris.3704Chris.3704 USUniversity ✭✭

    Hi guys,

    Luckily I stumbled across the solution for the Firebase messaging issue.

    This worked for me:

    Add the following to your AndroidManifest.xml manually:

      android:permission="" >
            <action android:name="" />
            <action android:name="" />
            <category android:name="${applicationId}" />
Sign In or Register to comment.