应用程序从异步方法崩溃



我正在创建一个应用程序,该应用程序以 JSON 格式从 Web 服务器请求少量数据,使用 Json.net 反序列化数据,并返回自定义对象的列表。我正在使用安卓手机调试应用程序。

然后使用创建的列表创建列表视图。UI 代码似乎适用于插入到列表中的预制对象,而不是异步方法。异步方法使应用程序崩溃。

public partial class Membership : ContentPage
{
    int increment = 1;
    public Membership()
    {
        //begin task
        var task = GetMembers(increment);
        //irrelevant stuff happening
        //wait for task to complete to continue execution
        List<Person> people = task.Result;

        // Create the ListView.
        ListView listView = new ListView
        {
            // Source of data items.
            ItemsSource = people,
            // Define template for displaying each item.
            // (Argument of DataTemplate constructor is called for 
            //      each item; it must return a Cell derivative.)
            ItemTemplate = new DataTemplate(() =>
            {
                // Create views with bindings for displaying each property.
                Label nameLabel = new Label();
                Label statusLabel = new Label();

                nameLabel.SetBinding(Label.TextProperty, "name");
                statusLabel.SetBinding(Label.TextProperty, "status");
                // Return an assembled ViewCell.
                return new ViewCell
                {
                    View = new StackLayout
                    {
                        Padding = new Thickness(0, 5),
                        Orientation = StackOrientation.Horizontal,
                        Children =
                            {
                                //boxView,
                                new StackLayout
                                {
                                    VerticalOptions = LayoutOptions.Center,
                                    Spacing = 0,
                                    Children =
                                    {
                                        nameLabel,
                                        statusLabel
                                    }
                                    }
                            }
                    }
                };
            })
        }; 
        // Build the page.
        this.Content = new StackLayout
        {
            Children =
            {
                header,
                listView
            }
        };

    }

以及有问题的异步任务:

async Task<List<Person>> GetMembers(int increment)
{
        string jsonString;
        using (var client = new HttpClient())
        {
            //gets the members from the server in json format
            //increment defines which set of members (1-50, 51-100, etc)
            var responseString = await client.GetStringAsync("GENERIC URL" + "increment=" + increment.ToString());
            jsonString = responseString;
        }
        List<Person> memberList = JsonConvert.DeserializeObject<List<Person>>(jsonString);
        return memberList;
}

现在,我已经通过绕过异步任务并创建几个预定义人员的列表来测试此代码,并且它工作得很好。

我理解使用任务。结果;方法将阻止应用程序,直到异步任务完成,但是,当单元测试时,速度没有问题,所以我有点困惑。任何帮助将不胜感激。

因为你说:

"没有错误消息,它只是冻结。">

在评论中,我相信你在这里有一个僵局。.Result.Wait()的问题在此SO-Ticket中有很好的描述:

等待工作,但调用任务。结果挂起/死锁

您的续集尝试访问被 .Result 阻止的上下文。您可以像这样重建您的方法:

public async Task InitializeMembership()
{
    //begin task
    var task = GetMembers(increment);
    //irrelevant stuff happening
    //wait for task to complete to continue execution
    List<Person> people = await task;
    //Do further stuff    
}

如您所见,我会使用方法而不是构造函数,因为我认为异步构造函数不是最佳实践。我希望这可以解决您的问题。

最新更新