3

我目前正在使用 Xamarin 免费试用版开发概念验证应用程序,并且遇到了一个相当有趣的小问题......这是我在可移植类库中使用的代码:

using System;
using System.Net;
using Newtonsoft.Json;

namespace poc
{
    public class CurrentWeatherInformation
    {

        public string WeatherText { get; set; }

        public CurrentWeatherInformation (string cityName)
        {
            // api.openweathermap.org/data/2.5/weather?q=Leeds
            var request = (HttpWebRequest)WebRequest.Create(string.Format("http://api.openweathermap.org/data/2.5/weather?q={0}", cityName));
            request.ContentType = "application/json";
            request.Method = "GET";
            object state = request;

            var ar = request.BeginGetResponse (WeatherCallbackMethod, state);
            var waitHandle = ar.AsyncWaitHandle as System.Threading.ManualResetEvent;

            waitHandle.WaitOne();
        }

        public void WeatherCallbackMethod(IAsyncResult ar)
        {
            object state = ar.AsyncState;
            var request = state as HttpWebRequest;
            var response = request.EndGetResponse(ar);
            var data = new System.IO.StreamReader (response.GetResponseStream ()).ReadToEnd ();
            this.WeatherText = data;
        }

    }
}

本质上,我只是想针对 Web 服务调用并获得响应,但我注意到 Xamarin 无法使用旧方法执行此操作,而GetResponse()必须使用旧模式。嘘。BeginGetResponse()EndGetResponse()IAsyncResult

无论如何,我的问题是我等待之后waitHandle的代码在回调中的代码之前执行,我不明白为什么。这正是我们等待处理的原因!

谁能发现我确信会被一个傻瓜证明是一个简单的错误?

4

1 回答 1

2

在 Windows Phone 上,您被迫使用异步 API。当您尝试在主线程上同步等待异步方法的结果时,您可能会陷入无限循环。当你做昂贵的事情时async使用。await这是进行异步工作的常见模式。

看一些教程:

https://visualstudiomagazine.com/articles/2013/10/01/asynchronous-operations-with-xamarin.aspx

http://developer.xamarin.com/recipes/android/web_services/sumption_services/call_a_rest_web_service/

如何使用带有 Xamarin 或 Dot42 的 async/await 在 C# 中实现 Android 回调?

https://github.com/conceptdev/xamarin-forms-samples/blob/master/HttpClient/HttpClientDemo/GeoNamesWebService.cs

于 2015-08-27T10:27:10.733 回答