如何在WPF活动处理程序中使用async调用

发布于 2025-01-27 09:33:51 字数 1084 浏览 1 评论 0原文

我在WPF中使用异步调用的WPF中有这个活动处理程序。

private void Button_Click(object sender, RoutedEventArgs e)
{
    var folderStructure = restApiProvider.GetFolderStructure();
}

这是getFolderStructure()的实现:

public async Task<IList<string>> GetFolderStructure()
{
    var request = new RestRequest(string.Empty, Method.Get);
    var cancellationTokenSource = new CancellationTokenSource();
    var response = await client.GetAsync(request, cancellationTokenSource.Token);

    return JsonConvert.DeserializeObject<IList<string>>(response.Content);
}

我需要从getFolderStructure()中获取数据以继续在应用程序中,但这是我获得的输出:

如果我添加foldersstructure.wait();呼叫无法完成,并且整个应用程序都会被卡住。但是,如果我更改var foldersstructure = restapiprovider.getFolderStructure(); restapiprovider.getFolderStructure(); 呼叫立即完成并且固定不发生。

我想念什么?

I have this event handler in WPF with async call.

private void Button_Click(object sender, RoutedEventArgs e)
{
    var folderStructure = restApiProvider.GetFolderStructure();
}

Here is the implementation of GetFolderStructure():

public async Task<IList<string>> GetFolderStructure()
{
    var request = new RestRequest(string.Empty, Method.Get);
    var cancellationTokenSource = new CancellationTokenSource();
    var response = await client.GetAsync(request, cancellationTokenSource.Token);

    return JsonConvert.DeserializeObject<IList<string>>(response.Content);
}

I need to get the data from GetFolderStructure() in order to continue in the app but this is the output I get:
enter image description here

If I add folderStructure.Wait(); the call doesn't complete itself and the whole app get stuck. However if I change var folderStructure = restApiProvider.GetFolderStructure(); to restApiProvider.GetFolderStructure(); the call is completed immediately and stuck doesn't occure.

What am I missing?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

忘年祭陌 2025-02-03 09:33:51

使调用方法异步并等待结果:

private async void Button_Click(object sender, RoutedEventArgs e)
{
    var folderStructure = await restApiProvider.GetFolderStructure();
}

Make the calling method async and await the result:

private async void Button_Click(object sender, RoutedEventArgs e)
{
    var folderStructure = await restApiProvider.GetFolderStructure();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文