如何阻止异步任务运行[Xamarin]

时间:2016-12-20 14:31:41

标签: c# android asynchronous xamarin task

我有几个片段,每个片段都有一个异步任务函数,可以将图像加载到列表视图中。

问题是如果用户在async仍在执行时切换到另一个片段,则会导致NullPointerException。

我的问题是,如何停止运行异步任务功能?

这是我的异步任务功能:

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

图像被添加到列表中的过度异步OnResume(我必须进行OnResume异步,否则它不会等待):

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

0 个答案:

没有答案
相关问题