Home > Software design >  Calling Web API with Async /Await
Calling Web API with Async /Await

Time:09-25

I have a web api endpoint i am consuming using Xamarin Community Toolkit TabView. On Tab selection change i am calling/making a get Request.

The Request

  public async void loadOtherData(string grp)
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("https://xxxx.somee.com/api/GetTaskByStatus/");
            var responseTask = client.GetAsync(grp);

            responseTask.Wait();

            var res = responseTask.Result;
            if (res.IsSuccessStatusCode)
            {
                string readTask = await res.Content.ReadAsStringAsync();
                var data = JsonConvert.DeserializeObject<ObservableCollection<api>>(readTask);
                Items1 = new ObservableCollection<api>(data);
                AcceptList.ItemsSource = Items1;
            }
        }
    }

This Method loadOtherData("") gets the api data and binds to a list.

I have a Tabview and when i change selection tab i call the method

    private void AssignedTab_TabTapped(object sender, TabTappedEventArgs e)
    {
       await loadOtherData("Assigned");
    }

 private void PendingTab_TabTapped(object sender, TabTappedEventArgs e)
    {
       await loadOtherData("Pending");
    }

The Challenge i am having is that when i switch from one Tab to the other the Tab freezes for a few seconds until the Api data is reterived and binded.

What i want is for the tab to switch without freezes while it loads the data from the Api

I am using Code behind, how do i approach this?

CodePudding user response:

The .Wait() method blocks the current thread until the task has completed. You should be using the await keyword with async methods instead, which frees your program to perform other operations until the asynchronous task is completed, at which point execution resumes at the next line after where the await is used.

From https://docs.microsoft.com/en-gb/dotnet/api/system.threading.tasks.task.wait?view=net-5.0#System_Threading_Tasks_Task_Wait:

Wait is a synchronization method that causes the calling thread to wait until the current task has completed. If the current task has not started execution, the Wait method attempts to remove the task from the scheduler and execute it inline on the current thread. If it is unable to do that, or if the current task has already started execution, it blocks the calling thread until the task completes. For more information, see Task.Wait and "Inlining" in the Parallel Programming with .NET blog.

Modify your code to this:

        ...
        var res = await client.GetAsync(grp);
        ...
  • Related