1

I have several fragments and every fragment has an async Task function that loads images into a listview.

The issue is that if the user switches to another fragment while the async is still executing, this results in NullPointerException.

My question is, how would i stop an async Task function from running?

This is my async Task function :

public async Task<Bitmap> GetImageBitmapFromUrl(Uri url)
        {
            try
            {
                var client = new HttpClient(new NativeMessageHandler());
                var res = await client.GetAsync(url).ConfigureAwait(false);
                if (res.IsSuccessStatusCode)
                {
                    using (var data = await res.Content.ReadAsStreamAsync().ConfigureAwait(false))
                    {
                        return await BitmapFactory.DecodeStreamAsync(data).ConfigureAwait(false);
                    }
                }
            }
            catch
            {

            }
            return null;
        }

And the images are added to the list in an overidden async OnResume(i had to make the OnResume Async or else it would not await) :

public override async void OnResume()
        {
            base.OnResume();

            for (int i = 0; i < times; i++)
            {
                var mar = await GetImageBitmapFromUrl(new Uri(mitems[i].img_link));
                bitys[i] = mar;
                mitems[i].Image = bitys[i];
                adapter.update(mitems);
                Activity.RunOnUiThread(() => adapter.NotifyDataSetChanged());
            }
        }
Goldberg
  • 19
  • 6
  • With c# you need cancellation tokens, similar question can be found here: http://stackoverflow.com/questions/10134310/how-to-cancel-a-task-in-await – Milen Dec 20 '16 at 15:33

0 Answers0