OData永远以Xamarin形式挂起

时间:2014-10-16 14:40:26

标签: xamarin odata xamarin.forms

我正在尝试使用Xamarin表单中的Simple.OData.Client从Nortwind URL获取数据。应用程序永远挂起。简单的项目源代码位于以下链接:Download

using Simple.OData.Client;

public async void InitializeDataService(){

    try {
        mODataClient = new ODataClient("http://services.odata.org/Northwind/Northwind.svc/");
    }

    catch {
        await DisplayAlert("Error", "Connection Error", "OK", "Cancel");
        System.Diagnostics.Debug.WriteLine("ERROR!");
    }
}

public async void GetDataFromOdataService (string myDataClicked){

    try {
        myCustomers= mODataClient.For(myDataClicked).Top(10).FindEntriesAsync().Result;
    }

    catch {
        await DisplayAlert("Error", "Connection Error", "OK", "Cancel");
        System.Diagnostics.Debug.WriteLine("ERROR!");
    }
}

更新:1 我已根据Pete建议更新了我的代码。仍然永远挂起。

private ODataClient mODataClient;
private IEnumerable <IDictionary<string,object>> myCustomers;
public ObservableCollection <Customer>Customers { get; set;}
public string myDataString;

public MyDataServices (string myDataClicked)
{
    Title="Customers";
    myDataString = myDataClicked;
    callServices();
}

public async Task callServices()
{
    await InitializeDataService ();
    await GetDataFromOdataService (myDataString);   
}

public async Task InitializeDataService(){

    try {
        mODataClient = 
            new ODataClient("http://services.odata.org/Northwind/Northwind.svc/");
    }
    catch {
        await DisplayAlert("Error", "Connection Error", "OK", "Cancel");
        System.Diagnostics.Debug.WriteLine("ERROR!");
    }
}

public async Task GetDataFromOdataService (string myDataClicked){

    try {
        myCustomers= mODataClient.For(myDataClicked).Top(10).FindEntriesAsync().Result;
    }
    catch {
        await DisplayAlert("Error", "Connection Error", "OK", "Cancel");
        System.Diagnostics.Debug.WriteLine("ERROR!");
    }
}

2 个答案:

答案 0 :(得分:2)

我怀疑这是因为您尝试调用异步并使其同步而暂停。

在你这样做的地方,我认为你现在正在做这个测试,之后你会扩展到现在你的变量只是该函数的本地变量。

请尝试public static async Page GetMainPage(),然后更改为: -

var customers= await mODataClient.For("Customers").Top(10).FindEntriesAsync();

因为它很可能挂在你以前的实现上。

请注意,您很可能必须执行异步声明并将等待添加到调用 GetMainPage()功能的页面中让所有这些工作。

真的 - 但是 - 我会把它当作任务&lt;&gt;在您正在显示的页面中等待它并进行等待。

更新1: -

问题与异步 / 等待问题有关。

数据任务被分离为一个单独的函数,返回任务&lt;&gt; ,随后在检索数据时更新 ListView.ItemsSource 控件。

答案 1 :(得分:1)

正如Pete所怀疑的那样,应用程序很可能因为您尝试同步运行而挂起。检查源代码并修改您调用的所有位置.Result或.Wait()。然后它应该工作。我知道这样的重构可能需要大量的代码重写,但这是要走的路。