Xamarin HttpClient 卡住并且不返回控制权

我不明白为什么主线程不交出控制权来处理结果。


public partial class NewTravelPage : ContentPage

    {

        public NewTravelPage()

        {

            InitializeComponent();

        }


        protected async override void OnAppearing()

        {

            var locator = CrossGeolocator.Current;

            var position = await locator.GetPositionAsync();


            var vanues = await VenueLogic.getVenues(position.Latitude, position.Longitude);

            venueListView.ItemsSource = vanues;


        }

    }

我调用方法 getVenues:


public class VenueLogic

    {

        public async static Task<List<Venue>> getVenues(double latitude, double longitude)

        {

            List<Venue> vanues = new List<Venue>();


            var url = VenueRoot.GenerateUrl(latitude, longitude);


            using (HttpClient client = new HttpClient())

            {

                var res = await client.GetAsync("https://stackoverflow.com"); 

                // here the code gives control to the main thread and stucks


                var response = await res.Content.ReadAsStringAsync();


                var venueRoot = JsonConvert.DeserializeObject<VenueRoot> 

                                                                (response);


                vanues = venueRoot.response.venues as List<Venue>;

            }


            return vanues;

        }

    }

使用.NetStandard;请帮忙!我不明白僵局发生在哪里

http://img1.mukewang.com/64bb94800001339819141080.jpg

繁华开满天机
浏览 112回答 1
1回答

手掌心

您的async void非事件处理程序意味着您的即发即忘调用将无法捕获可能引发的任何异常。使用事件处理程序修复该问题public partial class NewTravelPage : ContentPage {    public NewTravelPage() {        InitializeComponent();        appearing += onAppearing;    }    protected override void OnAppearing() {        appearing(this, EventArgs.Empty);    }    event EventHandler appearing = delegate { };    private async void onAppearing(object sender, EventArgs args) {        try {            var locator = CrossGeolocator.Current;            var position = await locator.GetPositionAsync();
打开App,查看更多内容
随时随地看视频慕课网APP