0

我正在尝试按照 Windows Phone 8 中的标题进行操作,这就是我的做法:

private async void Application_Launching(object sender, LaunchingEventArgs e)
{
    var settings = IsolatedStorageSettings.ApplicationSettings;
    settings.Add("listofCurrency", await CurrencyHelpers.getJsonCurrency());
}

在货币助手中:

    public async static Task<Dictionary<string, double>> getJsonCurrency()
    {
        HttpClient client = new HttpClient();

        string jsonResult = await client.GetStringAsync("http://openexchangerates.org/api/latest.json?app_id=xxxxxxx");

        JSONCurrency jsonData = JsonConvert.DeserializeObject<JSONCurrency>(jsonResult);

        Dictionary<string, double> currencyCollection = new Dictionary<string, double>();

        currencyCollection = jsonData.Rates;

        return currencyCollection;

    }

当 MainPage 加载时,我立即从 CurrencyHelpers 调用另一个方法:

    public static KeyValuePair<double, double> getStorageCurrencyPairRates(string firstCurrency, string secondCurrency)
    {
        var settings = IsolatedStorageSettings.ApplicationSettings;
        double firstCurrencyRate = 1;
        double secondCurrencyRate = 1;

        Dictionary<string, double> currencyCollection = new Dictionary<string,double>();

        //needs some code here to check if "listofCurrency" already has JSONData stored in it.

        settings.TryGetValue<Dictionary<string,double>>("listofCurrency", out currencyCollection);

        foreach (KeyValuePair<string, double> pair in currencyCollection)
        {
            if (pair.Key == firstCurrency)
            {
                firstCurrencyRate = pair.Value;
            }

            else if (pair.Key == secondCurrency)
            {
                secondCurrencyRate = pair.Value;
            }
         }

        return new KeyValuePair<double, double>(firstCurrencyRate, secondCurrencyRate);          
    }
}

这个想法是我想将我的 JSON 数据存储到存储中,然后在可用时立即检索它,有什么想法吗?非常感谢您的帮助!

4

1 回答 1

0

您对 await 和 async 的思考方式是正确的,但是您在页面加载时通过调用另一个方法破坏了它的概念。Wilfred Wee 所说的也是错误的。

正确的方法是在 App.xamls.cs 中声明一个事件处理程序,如下所示:

public event EventHandler<bool> SettingsReady;

然后将您的 Application_Launching() 方法更改为以下内容:

private async void Application_Launching(object sender, LaunchingEventArgs e)
{
    var settings = IsolatedStorageSettings.ApplicationSettings;
    settings.Add("listofCurrency", await CurrencyHelpers.getJsonCurrency());

    if (SettingsReady!= null)
        SettingsReady(this, true);
}

现在在您的 MainPage.xaml.cs (CONSTRUCTOR - NOT WHEN LOADED) 中声明要在数据实际准备好时调用的回调函数:

    // Constructor
    public MainPage()
    {
        InitializeComponent();

        // Call back functions
        App.SettingsReady += App_SettingsReady;
    }

    void App_SettingsReady(object sender, bool e)
    {
        // Here call your function for further data processing
        getStorageCurrencyPairRates();
    }
于 2013-08-17T08:06:38.867 回答