Xamarin:在Web服务响应之前,如何防止导航到另一个页面

时间:2015-06-29 19:08:41

标签: c# android multithreading xamarin cross-platform

我尝试调用Web服务来检索将在下一页显示的数据。但是,页面在完成Web服务请求之前尝试显示空数据。 能帮帮我吧。

//代码

var tapGestureRecognizer = new TapGestureRecognizer();
tapGestureRecognizer.Tapped += async (s, e) =>
{                     
    getEmployeepage(mainContact.managerID);                 
    await Navigation.PushAsync(new ManagerDetailsPage(data()));             
};
manager.GestureRecognizers.Add(tapGestureRecognizer);

//检索数据的方法

public async void getEmployeepage(String searchvalue)
{
    EmployeeDetailsPage employeeDetailsPage = null;
    try
    { 
        var client = new System.Net.Http.HttpClient();

        client.BaseAddress = new Uri("http://..........");
        var response = await client.GetAsync("criterion?empId=" + searchvalue);
        string jsonString = response.Content.ReadAsStringAsync().Result;                   

        //rest of the logic            

    }
}

先谢谢。

2 个答案:

答案 0 :(得分:2)

你的方法应该是等待的。因此public async void getEmployeepage(String searchvalue)变为public async Task getEmployeepage(String searchvalue)。有了这个,你可以这样等待你的方法:

await getEmployeepage(mainContact.managerID);

使用Async属性扩展异步方法名称也是一种很好的做法。您的方法名称将更改为GetEmployeePageAsync。另一个好的做法是总是返回一个任务。从而使方法等待。这种模式的唯一例外是事件处理程序。

答案 1 :(得分:1)

您需要getEmployeepage异步调用并将async void方法表单async Task更改为var tapGestureRecognizer = new TapGestureRecognizer(); tapGestureRecognizer.Tapped += async (s, e) => { await getEmployeepage(mainContact.managerID); await Navigation.PushAsync(new ManagerDetailsPage(data())); }; manager.GestureRecognizers.Add(tapGestureRecognizer);

public async Task getEmployeepage(String searchvalue)
{
    EmployeeDetailsPage employeeDetailsPage = null;
    try
    { 
        var client = new System.Net.Http.HttpClient();

        client.BaseAddress = new Uri("http://..........");
        var response = await client.GetAsync("criterion?empId=" + searchvalue);
        string jsonString = await response.Content.ReadAsStringAsync();                   

        //rest of the logic            

    }
}

&安培;

{{1}}