Quantcast
Channel: Xamarin.Forms — Xamarin Community Forums
Viewing all articles
Browse latest Browse all 77050

Correct way to cancel an async Task?

$
0
0

Lets say I have a search bar and a listView in a Content Page...
When I search for a text I run an async task that gets some info from a Rest Server.
But if I pop the page before the Task is completed I get an exception when it try to run something on MainThread.
A piece of the code:

        SearchBar searchBar = new SearchBar
                {
                    Placeholder = "Search",
                };

                searchBar.SearchButtonPressed += OnSearchBarButtonPressed;

                ListView listView = new ListView
                {
                    VerticalOptions = LayoutOptions.FillAndExpand,
                    RowHeight = 10,

                };

        async void OnSearchBarButtonPressed(object sender, EventArgs args)
            {

                SearchBar searchBar = (SearchBar)sender;
                string searchText = searchBar.Text;
                await Task.Run (async () => {
                    await GetInfo (searchText);

                });
            }

        private async Task GetInfo (string searchText)
        {

            searchList = await GetList (searchText);


            Device.BeginInvokeOnMainThread (async() => {

                        listView.ItemsSource = searchList;

            });
        }

        public static async Task<List<String>> GetList (string searchText)
        {

            //Get List throught Rest Server

            return searchList;
        }

To Cancel it I was trying to use a Cancelation Token...
I saw this topic and this tutorial and send a CancelationToken to my tasks as parameters and onDisapearing I called

          if (cts != null)
            {
                cts.Cancel();
            }

To Cancel the tasks but not sure if just passing the CancelationToken as an argument is enought and if Im doing right!

Any help?


Viewing all articles
Browse latest Browse all 77050

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>