Reputation: 19
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 data from the API, and binds it to a list.
I have a Tabview and when I change the selection tab, I call this 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 retrieved and bound.
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?
Upvotes: 0
Views: 2478
Reputation: 753
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.
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);
...
Upvotes: 3