我创建了一个 asp.net 的Web api。它工作得很好,用邮递员测试。我想在 wpf 数据网格上显示用户。代码如下:
public partial class ListUsers : Page
{
public ListUsers()
{
InitializeComponent();
GetData();
}
public void GetData()
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:1234/");
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("api/users").Result;
if (response.IsSuccessStatusCode)
{
var users = response.Content.ReadAsAsync<IEnumerable<Users>>().Result;
UserGrid.ItemsSource = users;
}
else
{
MessageBox.Show("Error Code" + response.StatusCode + " : Message - " + response.ReasonPhrase);
}
}
}
但不幸的是,它们在数据上的出现非常缓慢。一会儿,霜冻从应用程序上消失了。如何加速?
对不起,英语不好。
将方法设为async
:
public async Task GetData()
并await
服务器的响应:
var users = await response.Content.ReadAsAsync<IEnumerable<Users>>();
(您很少想直接致电.Result
。
这将允许应用程序主机在后台等待 I/O 操作时将控制权返回给 UI。