使用 Async /Await 调用 Web API

Calling Web API with Async /Await

我有一个正在使用 Xamarin Community Toolkit TabView 的 Web API 端点。在选项卡选择更改时,我是 calling/making 获取请求。

要求:

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

此方法 loadOtherData("") 从 API 获取数据并将其绑定到列表。

我有一个 Tabview,当我更改选择选项卡时,我调用了这个方法:

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

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

我遇到的挑战是,当我从一个选项卡切换到另一个选项卡时,选项卡会冻结几秒钟,直到检索并绑定 API 数据。

我想要的是选项卡在从 Api

加载数据时切换而不冻结

我正在使用隐藏代码,我该如何处理?

The .Wait() method blocks the current thread until the task has completed。您应该使用 await 关键字和 async 方法,这样您的程序就可以执行其他操作,直到异步任务完成,此时执行在 [=12 之后的下一行恢复=]被使用。

来自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.

将您的代码修改为:

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