在构造函数中调用异步方法? [英] Call asynchronous method in constructor?

查看:34
本文介绍了在构造函数中调用异步方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

总结:我想在构造函数中调用异步方法.这可能吗?

Summary: I would like to call an asynchronous method in a constructor. Is this possible?

详细信息:我有一个名为 getwritings() 的方法可以解析 JSON 数据.如果我只是在 async 方法中调用 getwritings() 并将 await 放在它的左边,一切都正常.但是,当我在页面中创建 LongListView 并尝试填充它时,我发现 getWritings() 令人惊讶地返回 nullLongListView 为空.

Details: I have a method called getwritings() that parses JSON data. Everything works fine if I just call getwritings() in an async method and put await to left of it. However , when I create a LongListView in my page and try to populate it I'm finding that getWritings() is surprisingly returning null and the LongListView is empty.

为了解决这个问题,我尝试将 getWritings() 的返回类型更改为 Task> 然后通过在构造函数中检索结果getWritings().Result.但是,这样做最终会阻塞 UI 线程.

To address this problem, I tried changing the return type of getWritings() to Task<List<Writing>> and then retrieving the result in the constructor via getWritings().Result. However, doing that ends up blocking the UI thread.

public partial class Page2 : PhoneApplicationPage
{
    List<Writing> writings;

    public Page2()
    {
        InitializeComponent();
        getWritings();
    }

    private async void getWritings()
    {
        string jsonData = await JsonDataManager.GetJsonAsync("1");
        JObject obj = JObject.Parse(jsonData);
        JArray array = (JArray)obj["posts"];

        for (int i = 0; i < array.Count; i++)
        {
            Writing writing = new Writing();
            writing.content = JsonDataManager.JsonParse(array, i, "content");
            writing.date = JsonDataManager.JsonParse(array, i, "date");
            writing.image = JsonDataManager.JsonParse(array, i, "url");
            writing.summary = JsonDataManager.JsonParse(array, i, "excerpt");
            writing.title = JsonDataManager.JsonParse(array, i, "title");

            writings.Add(writing);
        }

        myLongList.ItemsSource = writings;
    }
}

推荐答案

最好的解决方案是承认下载的异步性质并为其设计.

The best solution is to acknowledge the asynchronous nature of the download and design for it.

换句话说,决定您的应用程序在下载数据时应该是什么样子.让页面构造器设置那个视图,然后开始下载.下载完成后更新页面以显示数据.

In other words, decide what your application should look like while the data is downloading. Have the page constructor set up that view, and start the download. When the download completes update the page to display the data.

我有一篇关于 异步构造函数 的博客文章,您可能会觉得有用.此外,一些 MSDN 文章;一个关于 异步数据绑定(如果你使用的是 MVVM),另一个关于 异步最佳实践(即,您应该避免async void).

I have a blog post on asynchronous constructors that you may find useful. Also, some MSDN articles; one on asynchronous data-binding (if you're using MVVM) and another on asynchronous best practices (i.e., you should avoid async void).

这篇关于在构造函数中调用异步方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆