微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

执行 HttpRequest 后跳过代码

如何解决执行 HttpRequest 后跳过代码

所以我对我的 API 进行 POST 调用获取多个对象,然后将这些对象添加到列表中并显示在 RecyclerView 中。问题是,在获得 var 结果 后,它会跳过该方法中剩余的全部代码并执行下一个方法 SetupRecyclerView。 catch 不会捕获任何异常。这段代码有什么问题?

async void GetPostList()
        {
            try
            {
                string url = "linkToMyWebService";
                var uri = new Uri(url);
                var request = new HttpRequestMessage
                {
                    Method = HttpMethod.Post,RequestUri = uri
                };

                httpclienthandler clientHandler = new httpclienthandler();
                clientHandler.ServerCertificateCustomValidationCallback = (sender,cert,chain,sslPolicyErrors) => { return true; };
                HttpClient client = new HttpClient(clientHandler);
                var result = await client.SendAsync(request);
                var contentBody = await result.Content.ReadAsstringAsync();
                List<postRetrieved> posts = JsonConvert.DeserializeObject<List<postRetrieved>>(contentBody);
                foreach (var post in posts)
                {
                    postModel newPost = new postModel();
                    newPost.username = post.fullName;
                    newPost.description = post.postTitle;
                    newPost.city = post.postCity;
                    postList.Add(newPost);
                }
            }
            catch
            {

            }

        }


        void SetupRecyclerView()
        {
            postRecyclerView.SetLayoutManager(new Android.Support.V7.Widget.linearlayoutmanager(postRecyclerView.Context));
            postAdapter = new PostAdapter(MainScreenPosts);
            postRecyclerView.SetAdapter(postAdapter);
        }

解决方法

可能是关于 Catch。正在返回一些错误,并且一个空的 catch 会导致该方法被跳过。 您可以在“异常设置”中启用“公共语言运行时异常”或在捕获中记录错误。这将帮助您获得有关代码中出现问题的更多详细信息。

,

好吧,问题在于 GetPostList 是异步的。在等待获取对象列表的请求时,它开始执行需要这些对象运行的方法 SetupRecyclerView。我已经把它放在我的 trycatch 的 finally{} 块中,现在它工作正常。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。