Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to gracefully handle TaskCancelledException while using SearchBox in Windows 8.1

I am using a searchbox to which I will load a list of names.

My code behind

private async void SearchBox_SuggestionsRequested(SearchBox sender, SearchBoxSuggestionsRequestedEventArgs args)
    {
        if (string.IsNullOrEmpty(args.QueryText))
        {
            return;
        }
        var collection = args.Request.SearchSuggestionCollection;
        if(oldquery != args.QueryText && args.Request.IsCanceled == false)
        {
            var deferral = args.Request.GetDeferral();
            try
            {
                oldquery = args.QueryText;

                var listOfBanks = await addFIPageViewModel.GetBanksOnQuery();

                foreach (Institution eachBank in listOfBanks)
                {
                    collection.AppendQuerySuggestion(eachBank.Name);
                }
            }

            //JUST Logging and ignoring. Can I handle it in a better way
            catch(Exception e)
            {
                Debug.WriteLine(e.StackTrace);
            }
            finally
            {
                deferral.Complete();
            }

        }
    }

An exception of type 'System.Threading.Tasks.TaskCanceledException' A task was canceled. is occuring in the line

var listOfBanks = await addFIPageViewModel.GetBanksOnQuery();

which I am simply ignoring as you see.

Is there a better way to handle this?

I was unable to identify the root cause of this problem. Could someone guide if this is the right way to call an async method inside SearchSuggestionRequested.

like image 428
HelpMatters Avatar asked Feb 01 '26 17:02

HelpMatters


1 Answers

Your code looks fine to me. I'd catch the TaskCanceledException explicitly though to make sure I do not ignore other exceptions unintentionally.

try
{
    // like above 
}
catch(TaskCanceledException e)
{
    Debug.WriteLine("Task cancelled: " + e.Message);
}
finally
{
    deferral.Complete();
}
like image 102
Silverstein Avatar answered Feb 03 '26 08:02

Silverstein