Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/webpack/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 异步方法导致应用程序崩溃_C#_Xamarin_Xamarin.forms - Fatal编程技术网

C# 异步方法导致应用程序崩溃

C# 异步方法导致应用程序崩溃,c#,xamarin,xamarin.forms,C#,Xamarin,Xamarin.forms,我正在创建一个应用程序,它以JSON格式从Web服务器请求少量数据,使用JSON.net反序列化数据,并返回自定义对象的列表。我正在使用android手机调试应用程序 然后使用创建的列表创建listview。ui代码似乎可以处理插入列表中的预制对象,而不是异步方法。异步方法使应用程序崩溃 public partial class Membership : ContentPage { int increment = 1; public Membership() {

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

然后使用创建的列表创建listview。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
            }
        };


    }
公共部分类成员资格:ContentPage
{
int增量=1;
公众会员资格()
{
//开始任务
var task=GetMembers(增量);
//不相干的事情发生了
//等待任务完成以继续执行
列出人员=任务。结果;
//创建ListView。
ListView ListView=新建ListView
{
//数据项的来源。
ItemsSource=人,
//定义用于显示每个项目的模板。
//(需要调用DataTemplate构造函数的参数
//每个项目;它必须返回一个单元格导数。)
ItemTemplate=新数据模板(()=>
{
//创建具有用于显示每个属性的绑定的视图。
标签名称标签=新标签();
标签状态标签=新标签();
namelab.SetBinding(Label.TextProperty,“name”);
statusLabel.SetBinding(Label.TextProperty,“status”);
//返回一个组合的ViewCell。
返回新的ViewCell
{
视图=新堆栈布局
{
填充=新厚度(0,5),
方向=堆叠方向。水平,
孩子们=
{
//boxView,
新堆栈布局
{
垂直选项=布局选项。中心,
间距=0,
孩子们=
{
姓名标签,
状态标签
}
}
}
}
};
})
}; 
//构建页面。
this.Content=newstacklayout
{
孩子们=
{
标题,
列表框
}
};
}
以及所讨论的异步任务:

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;
}
异步任务GetMembers(int增量) { 字符串jsonString; 使用(var client=new HttpClient()) { //以json格式从服务器获取成员 //增量定义了哪一组成员(1-50、51-100等) var responseString=await client.GetStringAsync(“通用URL”+“increment=“+increment.ToString()); jsonString=响应字符串; } List memberList=JsonConvert.DeserializeObject(jsonString); 返回成员列表; } 现在,我绕过异步任务,创建了几个预定义人员的列表,对这段代码进行了测试,效果很好

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

因为您说:


“没有错误消息,它只是冻结。”

在评论中,我确信您在这里遇到了死锁情况。
.Result
.Wait()
的问题在本SO通知单中有详细描述:

继续尝试访问被
.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    
}
公共异步任务初始化成员身份()
{
//开始任务
var task=GetMembers(增量);
//不相干的事情发生了
//等待任务完成以继续执行
列出人员=等待任务;
//做更多的事情
}

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

您有任何错误消息吗?什么意味着应用程序崩溃?请确保该任务。结果可能会导致死锁:没有错误消息,它只是冻结。我相信您可能对错误消息是正确的死锁部分。我将不得不研究执行此任务的其他方法。谢谢。是的,这是一个死锁,因为两个线程想要访问相同的上下文。您只需等待调用并使成员方法异步。我将其作为答案发布,因此它的文档记录得更好。Sebi您是100%正确的,我感谢您的帮助。我解决了主要问题d无法将异步级联到顶级方法成员身份,因为它本质上是我的主函数,不能异步。将ui代码放入异步InitializeMembership()函数可以解决此问题。@BHigzz欢迎您。请不要忘记将答案标记为已解;-)。